Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to allow duplicate keys in php array [duplicate]

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?

like image 938
sudh Avatar asked Mar 26 '11 21:03

sudh


People also ask

Can array have duplicate keys PHP?

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.

Can associative array have same key?

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.

What is Array_keys () used for in PHP?

The array_keys() function returns an array containing the keys.


2 Answers

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") ); 
like image 63
Mike Lewis Avatar answered Sep 23 '22 12:09

Mike Lewis


$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.

like image 23
Matthew Avatar answered Sep 25 '22 12:09

Matthew