Array: store multiple values โ€‹โ€‹per key

I am trying to add two values โ€‹โ€‹with the same key, but this did not work. It turned the old value upside down. Is it not possible to add more than one value with the same key, and when retrieving by key, I get a linked list that I can repeat to get all the different values?

+4
source share
3 answers

Not unless you actually store the array as a value. Hashtables in PHP displays a key to a single value. This value may be an array, but you must build the array yourself. You might consider creating a class for this.

+1
source

the easiest option: wherever you use $array[$key]=... , replace it with $array[$key][]=...

+11
source

You can create a wrapper function:

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

So you just create a two-dimensional array. You can get a โ€œlinked listโ€ (another array) using regular access to the $array[$key] .

Whether this approach is convenient is up to you.

+1
source

Source: https://habr.com/ru/post/1332741/


All Articles