Search code examples
phparraysmultidimensional-array

How to add a new column to each row of a 2d array?


I have an array that looks like this:

$array = Array (
    [0] => Array ( [site_id] => 89193)
    [1] => Array ( [site_id] => 89093)
    [2] => Array ( [site_id] => 3059 )
)

What I want to do is to add a new pair to the array, how can I do so?

For example, next to site_id, I want to add the key [site_name] and its value.


Solution

  • foreach ($array as &$child) {
        $child['site_name'] = $value;
    }
    

    or, without references:

    foreach (array_keys($array) as $key) {
       $array[$key]['site_name'] = $value;
    }