note 119633 added to migration70.incompatible
| From: | viktor dot csiky at nospam dot nospam dot eu | Date: | Thu, 21 Jul 2016 11:16:11 +0000 |
| Subject: | note 119633 added to migration70.incompatible | ||
| Groups: | php.notes | ||
| Request: | Send a blank email to php-notes+get-206065@lists.php.net to get a copy of this message | ||
It is stated:
"foreach by-value operates on a copy of the array
When used in the default by-value mode, foreach will now operate on a copy of the array being
iterated rather than the array itself. This means that changes to the array made during iteration
will not affect the values that are iterated."
Please note that this is not exactly true. New foreach operates on a copy of the array, by-value or
by-reference. It seems that in the latter case, the array copy is simply moved over (to) the
original array before it is presumably destroyed.
As a consequence of this, you may not "dereference" an array containing values - e.g. for
use with ReflectionMethod::invokeArgs() or the good ole' call_user_func().
Consider the snippet below:
<?php
function deref(Array $inputArray)
{
$retVal = [];
foreach ($inputArray as &$inputValue)
{
$retVal[] = $inputValue;
}
return $retVal;
}
?>
As of PHP 7.0, this *will no longer work*. You will get the usual suspect:
PHP Warning: Parameter n to whatever() expected to be a reference, value given in baz.php on line x
You need to convert it to explicitly reference the original array:
<?php
function deref(Array $inputArray)
{
$retVal = [];
foreach ($inputArray as $inputKey => $inputValue)
{
$retVal[$inputKey] = &$inputArray[$inputKey];
}
return $retVal;
}
?>
PLEASE NOTE that this might have the unforeseen consequence of your code not working anymore in php
versions less than 5.3 (that is, 5.2 and below).
----
Server IP: 72.52.91.14
Probable Submitter: 109.61.74.220
----
Manual Page -- http://php.net/manual/en/migration70.incompatible.php
Edit -- https://master.php.net/note/edit/119633
Del: integrated -- https://master.php.net/note/delete/119633/integrated
Del: useless -- https://master.php.net/note/delete/119633/useless
Del: bad code -- https://master.php.net/note/delete/119633/bad+code
Del: spam -- https://master.php.net/note/delete/119633/spam
Del: non-english -- https://master.php.net/note/delete/119633/non-english
Del: in docs -- https://master.php.net/note/delete/119633/in+docs
Del: other reasons-- https://master.php.net/note/delete/119633
Reject -- https://master.php.net/note/reject/119633
Search -- https://master.php.net/manage/user-notes.php