1

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 ) )
1
  • 2
    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. Commented Mar 31, 2016 at 9:33

2 Answers 2

1

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"

Sign up to request clarification or add additional context in comments.

Comments

0

You are using the reference operator (&), due to that

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

array converts to

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

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

If you remove the & from the for-each the selected key will not reflect from the $types array.

1 Comment

thanks, I think Gokul Shinde answer is one I was looking for .

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.