关于循环范围中的PHP引用

时间:2016-03-31 09:27:45

标签: php

我想知道为什么这段代码会像这样工作。 为什么更改变量名称有所不同? 不应仅仅在foreach范围内可用吗?

$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 ) )

2 个答案:

答案 0 :(得分:1)

正确答案是有问题的评论。 "一旦你在php中声明变量,它将一直可用到脚本结束。同样的事情适用于For和Foreach循环中的变量声明。这些变量也可用到脚本结束。因此,在您的情况下,在foreach循环中存储在$ t中的最后一个值将在脚本的其余部分中可用。 - Gokul Shinde 3月31日9:33"

答案 1 :(得分:0)

由于

,您正在使用引用运算符(&)
$types = array(
0 => array('name'=>'One'),
1 => array('name'=>'Two')); 

数组转换为

$types = array(
0 => array('name'=>'One'),
1=> array('name'=>'Two', 'selected' => 1);

foreach($types as $t){
if ($t['name']=='Two') $t['selected'] = true;}

如果删除&从for-each中选择的键不会从$ types数组中反映出来。