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

    ?>
1
  • foreach ($arr as &$key) Commented Oct 3, 2019 at 13:08

3 Answers 3

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);
}
Sign up to request clarification or add additional context in comments.

Comments

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

Comments

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.

1 Comment

Yeah. Edited my answer.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.