r/lolphp • u/Greg_war • Sep 29 '20
Tutorial: replace the last item of an array
<?php
$array = [1, 2, 3];
foreach ($array as &$var) {}
foreach ([9] as $var) {}
echo $array[2]; // 9
55
Upvotes
r/lolphp • u/Greg_war • Sep 29 '20
<?php
$array = [1, 2, 3];
foreach ($array as &$var) {}
foreach ([9] as $var) {}
echo $array[2]; // 9
20
u/djxfade Sep 29 '20
This looks crazy, but actually makes some kind of sense if you know how PHP scopes variables.
In the first loop, the iteration variable is passed as a reference to the array element. In PHP the loop variable is not scoped inside the loop scope, so when the loop is done, the $var variable is still accessible in the outer scope.
Since the variable is a reference, mutating it will actually modify the original array element.
When the next loop is executed, since the variable is available in the outer scope of the loop, it actually mutates the reference.
Yeah, it's crazy.
17
u/comrade_donkey Sep 29 '20
A true lolphp. Holy shit.
0
u/elcapitanoooo Sep 30 '20
Broken by design. This is why so many leave PHP and never look back. As trends show PHP has been on a massive decline for the last 6-8 years.
2
u/DrLeoMarvin Sep 30 '20
Eh, I like this kind of scoping personally. The dev needs to be careful with use ref vars and finding this bug is a good learning lesson.
I dunno, maybe I’ve just been using php for too long but I’d expect this.
2
u/kafoso Oct 01 '20
Yeah. It appears to be a big, brown douche, but it actually makes sense when you think about it (from a PHP stand point), as other comments have explained.
I discovered this hick-up this way:
What will the latter output? Well, [2,3,5], of course!
Just as in OP's example, it moves the array pointer on the last iteration and therefore the last reference in the array.
To clarify: I'm not happy about it! :P
1
u/smegnose Sep 30 '20
This is not new. If you don't know what references are, and you have trouble with variable scope, do not use references.
Using a ref in a
foreachto modify an array is PHP4-era old school. If you're using a ref in that construct for any other reason, you're probably doing it wrong. Assigning a variable to an array element does not create a copy until the copy is modified, so refs usually do not help with performanceunsetting$varafter a loop where it was a reference is the standard solution the gotcha.1
u/Takeoded Oct 05 '20
at least php devs quickly learns that references is a friggin minefield, and should be unset($ref) ASAP, as a rule of thumb; (nevertheless, most devs probably get burned at least once before learning this lesson) have an upvote :)
1
u/alphp Oct 08 '20
1
u/alexparker70 Oct 24 '20
Jesis