Answer the question
In order to leave comments, you need to log in
Why is this happening with foreach stdClass in php?
Can you please tell me why, as a result of executing this code, when the value of the $n object changes in the foreach loop , the corresponding value of the $mvs object also changes?
$a = new stdClass();
$b = new stdClass();
$a->name = 'one';
$b->name = 'two';
$movies = new stdClass();
$movies->a = $a;
$movies->b = $b;
foreach ($movies as $mvs) {
echo $mvs->name.' - before<br />';
$n = $mvs;
$n->name = 'changed';
echo $mvs->name.' - after<br />';
}
$movies = array( 'a' => array( 'name' => 'one'), 'b' => array( 'name' => 'two') );
foreach ($movies as $mvs) {
echo $mvs['name'].' - before<br />';
$n = $mvs;
$n['name'] = 'changed';
echo $mvs['name'].' - after<br />';
}
Answer the question
In order to leave comments, you need to log in
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question