Re: PHP7 / foreach / references / ugly code / discrepancy to PHP 5.6
| From: | Martin Amps | Date: | Tue, 10 Nov 2015 19:08:55 +0000 |
| Subject: | Re: PHP7 / foreach / references / ugly code / discrepancy to PHP 5.6 | ||
| References: | 1 | Groups: | php.internals |
| Request: | Send a blank email to internals+get-89152@lists.php.net to get a copy of this message | ||
Here’s a 3v4l demonstrating this too:
https://3v4l.org/OXAd3 <https://3v4l.org/OXAd3>
> On Nov 10, 2015, at 8:48 AM, Philip Hofstetter <phofstetter@sensational.ch> wrote:
>
> Hi,
>
> I'm having a cause of slightly ugly code that runs differently from PHP 5.6
> to PHP 7 and I don't think this difference is documented, nor expected. As
> I'm not sure whether this is an intended change or not, I'm asking here
> firstr before making a bug report.
>
> The code in question is
>
> ----
> $b = [1, 2, 3];
>
> foreach($b ?: [] as &$v){
> $v = $v*2;
> unset($v);
> }
>
> var_dump($b);
> ----
> in PHP7, this produces
>
> array(3) {
> [0] =>
> int(1)
> [1] =>
> int(2)
> [2] =>
> int(3)
> }
>
> whereas in PHP 5.6 and earlier, this produces
>
> array(3) {
> [0] =>
> int(2)
> [1] =>
> int(4)
> [2] =>
> int(6)
> }
>
> what scares me about this is that in order to get the old behaviour in PHP7
> back, you just have to get rid of the ?: operator:
>
> foreach($b as &$v){
>
> is fine
>
> foreach($b ?: [] as &$v){
>
> is not.
>
> I guess this is related to
>
> http://php.net/manual/en/migration70.incompatible.php#migration70.incompatible.foreach.by-value
> or
>
> http://php.net/manual/en/migration70.incompatible.php#migration70.incompatible.foreach.by-ref,
> but I'm not entirely sure whether this is actually intended behaviour -
> it's certainly unexpected to me that applying ?: now always makes a copy
> whereas before it didn't.
>
> Philip
>
>
>
> --
> Sensational AG
> Giesshübelstrasse 62c, Postfach 1966, 8021 Zürich
> Tel. +41 43 544 09 60, Mobile +41 79 341 01 99
> info@sensational.ch, http://www.sensational.ch