Variable scope in PHP
Hello,
I have a problem to modify a variable in a method.
public function test() {
$composantes = [
[
'var1' => 0,
'var2' => 0,
],
[
'var1' => 0,
'var2' => 0,
],
];
...
foreach ($composantes as $composante) {
$composante['var1'] = 15;
}
...
print_r($composantes);
}
When I print the array, each variable is equal to 0.
How can I do to keep the new value (15) in the variables ?
Thanks for your help ;).
V
All you are doing is modifying the value of the temporary $composante variable; modify the $composantes variable instead by indexing into it:
foreach ($composantes as $index => $composante) {
$composantes[$index]['var1'] = 15;
}
@tykus Thank you very much ... what is the difference between both syntaxes ?
I think that my first one is a local variable and the second one (yours) is global inside the method, isn't it ?
Please or to participate in this conversation.