Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

array: store multiple values per key

Tags:

arrays

php

I once trying adding two values with the same key, but it didn't work. It overrode the old value. Isn't it possible to add more than one value with the same key, and when retrieving by key, I get a linked list which I can iterate to get all the different values?

like image 495
Ahmad Farid Avatar asked Dec 20 '10 10:12

Ahmad Farid


3 Answers

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

like image 169
user187291 Avatar answered Sep 21 '22 22:09

user187291


Not unless you actually store an array as the value. Hashtables in PHP map a key to one value. That value could be an array, but you have to build the array yourself. You might consider creating a class to do this for you.

like image 34
cdhowie Avatar answered Sep 20 '22 22:09

cdhowie


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 2-dimensional array. You can retrieve the "linked list" (another array) by normal array access $array[$key].

Whether this approach is convenient is up to you.

like image 40
Felix Kling Avatar answered Sep 20 '22 22:09

Felix Kling