In PHP, it is possible to iterate the elements of a array
through foreach
, both with the variable that contains it and 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;
}
You can also reference 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!" )
This code will generate a fatal error (which 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'm not sure if I'll be able to do this, but I'm not sure what to do. ".
Regarding this section, I have some doubts:
- How PHP treats, in each case, memory usage, values assigned to variables and values declared directly in loops , function returns, or in passing of parameters?
For example, how would you handle the% w / o of% passed by parameter in this example?
call_user_func_array('print_r', [$_POST, false]);
- Does the garbage collector come into the picture in cases like the one above, or is PHP already automatically discarding just after the line where the "temporary expression" is used?