How to allow duplicate keys in php array

sudh picture sudh · Mar 26, 2011 · Viewed 86.1k times · Source

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?

Answer

Mike Lewis picture Mike Lewis · Mar 26, 2011

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")
);