1

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"

2 Answers 2

7

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

1 Comment

Just to add, I was trying to achieve the same thing however, my array is associatively indexed and thus i wanted to add the value to the array AND associatively index it, this is what i did instead of the array_push line $t["new_value_name"] = "hello world";
5

No your not doing anything monumentally stupid. But if you want to change the array $test from within a foreach loop you must pass it as a reference.

foreach($test as &$t) // Pass by reference
{
    if( $t[1] == 1 )
    {
        array_push($t, "hello World"); // Now pushing to $t pushes to $test also
    }
}

Comments

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.