How to allow duplicate keys in php array [duplicate] How to allow duplicate keys in php array [duplicate] arrays arrays

How to allow duplicate keys in php array [duplicate]


You could have a single key that has a value of an array(aka a multi-dimensional array), which would contain all the elements with that given key. An example might be

$countries = array(  "United States" => array("California", "Texas"),  "Canada" => array("Ontario", "Quebec"));


$array[$key][] = $value;

You then access it via:

echo $array[$key][0];echo $array[$key][1];

Etc.

Note you are creating an array of arrays using this method.


The whole point of array is to have unique keys. If you want to store pairs of values, then:

$array[] = [$value1, $value2];

If you have many dupes, then this alternative will be more efficient:

<?phpif (array_key_exists($key, $array))     $array[$key]['occurrences']++; else     $array[$key] = ['value'=>$value, 'occurrences'=>1];