[RndTbl] php head-exploding moment

Trevor Cordes trevor at tecnopolis.ca
Fri Apr 26 17:16:10 CDT 2024


cat z.php

<?
$a=[0=>'2', 1=>'3'];

foreach ($a as $k=>&$v) {
  $v++;
  echo "$k,$v\n";
}

#unset($v);

echo "\n";

foreach ($a as $k=>$v) {
  echo "$k,$v\n";
}

echo "\n";
?>


Ok, guess what this prints out?

0,3
1,4

0,3
1,4

Right?  Wrong:

0,3
1,4

0,3
1,3


Until I stumble on this, see the Warning on second page.
https://www.php.net/manual/en/control-structures.foreach.php

This has got to be the most messed up fail by a language ever because in
no circumstances would any sane programmer ever expect this from any
language and in no way would any programmer ever want this behavior nor
could it ever be useful ever.

Perl (an early (first?) adopter of the "foreach") doesn't do this.

Surely php can "fix" this somehow.

The recommended "fix" is to uncomment the "unset" in the code to unlink
the reference.


More information about the Roundtable mailing list