How to allow php array to have duplicate keys? When I try to insert a key, value pair with already existing key it overwrites the value of corresponding previous key with the new value. Is there a way that I could maintain both duplicate keys having different values?
Arrays contains unique key. Hence if u are having multiple value for a single key, use a nested / multi-dimensional array. =) thats the best you got.
No, you cannot have multiple of the same key in an associative array. You could, however, have unique keys each of whose corresponding values are arrays, and those arrays have multiple elements for each key.
The array_keys() function returns an array containing the keys.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With