Push value to multidimensional array within a foreach loop

Chris Headleand picture Chris Headleand · Aug 17, 2012 · Viewed 11.2k times · Source

I have an array built from a database query. Based on the values posuition with the array I need to assign another string to it.

I thought an if statement within a foreach loop would be the way forward but I'm having some trouble.

Below is my code......

$test = array(
            array("test", 1),
            array("test2", 2),
            array("test4", 4),
            array("test5", 5),
            array("test3", 3),
            array("test6", 6)
            );


foreach($test as $t) {
if($t[1]==1){
    array_push($t, "hello World");
    }
}
print_r$test);

Everything seams to work other than the array_push. If i print_r($test) after the loop nothing has been added.

Am I doing something monumentally stupid here?...

This is what I get if i print_r($test)

Array
(
[0] => Array
    (
        [0] => test
        [1] => 1
    )

[1] => Array
    (
        [0] => test2
        [1] => 2
    )

[2] => Array
    (
        [0] => test4
        [1] => 4
    )

[3] => Array
    (
        [0] => test5
        [1] => 5
    )

[4] => Array
    (
        [0] => test3
        [1] => 3
    )

[5] => Array
    (
        [0] => test6
        [1] => 6
    )

)

I would be expecting test 1 to have a 3rd value in there called "hello world"

Answer

xdazz picture xdazz · Aug 17, 2012

Foreach loop works with a copy of an array. That's why if you want to change the original array, you should use reference.

foreach($test as &$t) {
   if($t[1]==1){
      array_push($t, "hello World"); // or just $t[] = "hello World";
   }
}