2

How can i add values to an array that is being contained by another array?

In the example code below, i am trying to add the string 'yellow' to both the arrays stored by $arr to form [ [ 'blue',yellow'] , ['green','yellow'] ]

In the first foreach loop, the word yellow has been successful pushed into the contained array which can be seen when i print out the array $key however

when i were to print the $arr out in the final foreach loop the yellow that i appended is gone


    $arr = array(array("blue"),array("green"));

    foreach ($arr as $key)
    {
        array_push($key,"yellow");
        print_r($key);
    }
    foreach ($arr as $key)
    {
        print_r($key);
    }

    ?>
ascsoftw
  • 3,466
  • 2
  • 15
  • 23
Yeo Bryan
  • 331
  • 4
  • 24

3 Answers3

3

Use reference on your foreach like so &$key to save your modification :

PHP make a copy of the variable in the foreach, so your $key is not actually the same as the one from your previous array.

From @Dharman :

& passes a value of the array as a reference and does not create a new instance of the variable.

So just do :

$arr = array(array("blue"),array("green"));

foreach ($arr as &$value)
{
    $value[]='yellow';
    print_r($value);
}
foreach ($arr as $value)
{
    print_r($value);
}
Dylan KAS
  • 4,840
  • 2
  • 15
  • 33
3

Here is foreach no key approach

$arr = [["blue"], ["green"]];
foreach ($arr as &$value)
       $value[]='yellow';        
print_r($arr);

Here is foreach with key approach

$arr = [["blue"], ["green"]];
foreach ($arr as $key=>$value)
       $arr[$key][]='yellow';        
print_r($arr);

Here is another approach using array_walk

$arr = [["blue"], ["green"]];
array_walk($arr, function(&$item) {
    $item[] = "yellow";
});
print_r($arr);

Here is the same thing with array_map

$arr = [["blue"], ["green"]];
$arr = array_map(function($item) {
    $item[] = "yellow";
    return $item;
}, $arr);
print_r($arr);

Output for all examples

Array
(
    [0] => Array
        (
            [0] => blue
            [1] => yellow
        )

    [1] => Array
        (
            [0] => green
            [1] => yellow
        )

)

And finally some performance tests speed and memory_usage

angel.bonev
  • 2,154
  • 3
  • 20
  • 30
0

You can also use array_map for this. See the below code for example.

$a = [["blue"],["green"]];

$b = array_map(function($n) {
    $n[] = "Yellow";
    return $n;
}, $a);

print_r($b);

Hope this helps.

Kishen Nagaraju
  • 2,062
  • 9
  • 17