2

Please consider this test:

$data=[["id"=>1,"text"=>"One"],["id"=>2,"text"=>"Two"]];
foreach((array)$data as &$iter)
    $iter["append"]=true;
print_r($data);

This is the output

Array
(
    [0] => Array
        (
            [id] => 1
            [text] => One
        )

    [1] => Array
        (
            [id] => 2
            [text] => Two
        )

)

I want to iter over an array and add another key inside the associative array, this is why $iter is passed by ref. I set the cast inside the "foreach" to be sure that an empty/null variable can be accepted without errors by foreach statement.

As you see in the output the foreach doesn't append the value, but if I remove the cast it works.

foreach($data as &$iter)
    $iter["append"]=true;
print_r($data);

This is the (right) output

Array
(
    [0] => Array
        (
            [id] => 1
            [text] => One
            [append] => 1
        )

    [1] => Array
        (
            [id] => 2
            [text] => Two
            [append] => 1
        )

)

I solved casting with a separate command outside the foreach, but my question is:

Is this a bug?

This test was run on PHP Version 5.6.14 (apache-2.4 windows-10)

3
  • 1
    The casted value can be a different value than what's inside the variable. So if it would work it would implicit assign: $variable = (array) $variable;. Commented Nov 22, 2015 at 17:29
  • Ok, but different values means different reference? Commented Nov 22, 2015 at 17:33
  • 1
    Exactly it's a value and you can't pass that via reference. Just as example if your variable holds: $variable = new StdClass; And your first code block works, would mean you have done an assignment implicit in the foreach header, which is not going to work, since after that you would have an array. Commented Nov 22, 2015 at 17:36

1 Answer 1

2

Casting some variable to other type (even the same) means that another variable is created.

So if you have:

$data = []; // some array here

Then doing (array)$data (what is the same as array($data) according to php-manual) means that you have new variable, so your:

foreach ((array)$data as &$iter)

works not with $data variable, but with some other variable, which still has same values as your $data.

So, you should explicitly cast to array:

$data = (array)$data;
foreach ($data as &$iter) {
    // do some stuff
}

And as manual said:

Array assignment always involves value copying.

so your $data and (array)$data are not the same.

Sign up to request clarification or add additional context in comments.

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.