このコードがこのように機能しているのは不思議です。 変数名を変更すると違いが生じるのはなぜですか? foreachスコープ内で$ tを使用できないようにする必要がありますか?ループスコープのPHPリファレンスについて
$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))
変数をPHPで宣言すると、スクリプトの終わりまで利用可能になります。 ForとForeachループで宣言する変数にも同じことが適用されます。これらの変数は、スクリプトが終了するまで利用可能です。したがって、foreachループで$ tに格納された最後の値は、スクリプトの残りの部分で使用できるようになります。 –