Ich frage mich, warum dieser Code so funktioniert. Warum ändert sich die Änderung des Variablennamens? Sollte nicht nur in foreach scope verfügbar sein?In Bezug auf PHP-Referenz in Schleife Bereich
$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))
Sobald Sie Variable in PHP deklarieren, wird es bis zum Ende des Skripts verfügbar sein. Das gleiche gilt für Variablen deklarieren in For und Foreach-Schleife. Diese Variablen sind auch bis zum Ende des Skripts verfügbar. In diesem Fall wird der letzte Wert, der in $ t in foreach loop gespeichert ist, im Rest des Skripts verfügbar sein. –