5
In PHP, it is possible to iterate the elements of a array
through the foreach
, both with the variable that contains it and with what PHP called "Temporary array Expression".
Example:
$myArray = ['a' => 'a', 'b' => 'b'];
foreach ($myArray as $key => $value) {
echo $value, PHP_EOL;
}
foreach(['a' => 'a', 'b' => 'b'] as $key => $value){
echo $value, PHP_EOL;
}
It is also possible to refer to each element of a array
, and that’s where my question comes in.
The code below works correctly:
$myArray = ['a' => 'a', 'b' => 'b'];
foreach ($myArray as $key => &$value) {
$value = sprintf('"%s!"', $value);
}
print_r($myArray); //imprime: Array ( [a] => "a!" [b] => "b!" )
Already this code will generate a fatal error (what I expected):
foreach (['a' => 'a', 'b' => 'b'] as $key => &$value) {
$value = sprintf('"%s!"', $value);
}
//Erro: Cannot create references to elements of a temporary array expression
I already know that trying to pass a statement by reference generates error, but my focus is not that, but rather that the error says in an excerpt "... Temporary array Expression...".
Regarding this passage, I have some doubts:
- What is the way in which PHP deals, in each case, with memory usage, values assigned to variables and values declared directly in loops, function returns or in passing parameters?
For example, how the array
passed by parameter in this example?
call_user_func_array('print_r', [$_POST, false]);
- The garbage collector enters the scene in cases like the above or PHP already automatically discards right after the line in which the "temporary expression is used"?
Related question in English (does not answer your question): http://stackoverflow.com/questions/24772958/is-there-a-rational-explanation-for-this-php-call-by-value-behavior-or-php-bug.
– bfavaretto