2

Why does casting $arr with (array) cause the array items to not be modified?

$arr = array(1, 2, 3, 4);
foreach ((array)$arr as &$value) {
    $value = $value * 2;
}

$arr should now equal [2,4,6,8] but for some reason it still equals [1,2,3,4].

3
  • 1
    Note: without (array), the original array is modified ( repl.it/repls/IllfatedBlueBetatest ) Commented Apr 27, 2018 at 23:20
  • 1
    Hypothesis: The (array) cast is a conversion that results in a new array, and modifications to such array are not visible to the original array // Test: repl.it/repls/ShamelessIllfatedFactorial // Conclusion: hypothesis holds. Commented Apr 27, 2018 at 23:20
  • Think about it like this : $arr = [1,2,3,4]; $newarr = (array) $arr; $newarr[] = 5; print_r($arr); You wouldn't expect $arr to have the new 5 entry, because $newarr = (array) $arr didn't change $arr to an array, it set $newarr to whatever $arr would be if cast as an array. Commented Apr 27, 2018 at 23:49

1 Answer 1

2

You are not modifying the original array, rather, the current looped iteration. If you wanted to modify the original array, you'd need to access the keys:

foreach ((array) $arr as $k => $v) {
    $arr[$k] = $v * 2;
}

It is possible to update the original by 'passing by reference' as confirmed by @user2864740 and the example that they have provided.

Thirdly, as @user2864740 pointed out in the original comment chain, using (array) seems to cause it to create a new array.

Live Example

Repl

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

4 Comments

PHP does modify "array variables", normally. The question is specific about the cast.
@user2864740 thanks for the confirmation, I'll update the post.
Here is the counter-case REPL (notice that there is no (array)) - repl.it/repls/IllfatedBlueBetatest
@user2864740 thank you very much, you beat me to it. I have updated the post with the relevant information.

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.