I'm wondering why this code is working like this. Why changing variable name makes difference ? Shouldn't $t be available just in foreach scope ?
$types = [
['name'=>'One'],
['name'=>'Two']
];
foreach($types as &$t){
if ($t['name']=='Two') $t['selected'] = true;
}
// now put that selection to top of the array
// I know this is not a good way to sort, but that's not the point
$_tmp=[];
// Version 1
// foreach($types as $v) if (isset($v['selected'])) $_tmp[] = $v;
// foreach($types as $v) if (!isset($v['selected'])) $_tmp[] = $v;
// Version 2
foreach($types as $t) if (isset($t['selected'])) $_tmp[] = $t;
foreach($types as $t) if (!isset($t['selected'])) $_tmp[] = $t;
print_r($_tmp);
//Version 1 : Array ( [0] => Array ( [name] => Two [selected] => 1 ) [1] => Array ( [name] => One ) )
//Version 2 : Array ( [0] => Array ( [name] => One ) [1] => Array ( [name] => One ) )
You are using the reference operator (&), due to that
array converts to
If you remove the & from the for-each the selected key will not reflect from the $types array.
Correct answer is in question comment. "Once you declare variable in php, it will be available till the end of script. Same thing apply for variables declare in For and Foreach loop. These variables also available till the end of script. So in you case last value stored in $t in foreach loop will be available in rest of the script. – Gokul Shinde Mar 31 at 9:33"