Code Snippet: How to store multiple values per key in PHP



Following code snippet is an example implementation in php that explains how we can store multiple values per key in PHP.

Example Implementation 1

You can create a wrapper function like below. So you just create a 2-dimensional array. You can retrieve the "linked list" (another array) by normal array access $array[$key].

<?php
function add_to_array($array$key$value) {
    if(
array_key_exists($key$array)) {
        if(
is_array($array[$key])) {
            
$array[$key][] = $value;
        }
        else {
            
$array[$key] = array($array[$key], $value);           
        }
    }
    else {
        
$array[$key] = array($value);
    }
}
?>