Jump to content

foreach loop


arunpatal

Recommended Posts

Hi,

 

  I was googling for updating a multidimensional array and found this....

<?php  
$test_array = array ( 
 		array ('item' => '1', 'qty' => '1'), 
  		array ('item' => '2', 'qty' => '1'), 
  		array ('item' => '3', 'qty' => '1') 
); 


foreach($test_array as &$value){
    if($value['item'] === '2'){
        $value['qty'] = 5;
        break;
    }
}
 
?> 

Can anyone explain me that what is &$value

 

When i remove & from of $value then the qty dose not change.....

Link to comment
https://forums.phpfreaks.com/topic/286195-foreach-loop/
Share on other sites

To put it in everyday terms.. when you iterate through an array with foreach by default php uses a copy of the keys and values of the array. So if you were for instance to do this:

 

$array = array(1,2,3);
foreach($array as $val) {
  $val++;
}
print_r($array);
All you are doing is incrementing a temporary value within the scope of the loop. It doesn't actually change $array, because $var is just a temp variable that is a copy of the value of the current index. So, print_r will still show $array as (1,2,3). However, if you include the & prefix, it tells php to reference (use) the actual array instead of the temp copy. So if you do this:

$array = array(1,2,3);
foreach($array as &$val) {
  $val++;
}
print_r($array);
print_r will now show $array as (2,3,4)

 

On a sidenote, iterating through an array like this is basically the equivalent of using array_map or array_walk

Link to comment
https://forums.phpfreaks.com/topic/286195-foreach-loop/#findComment-1468887
Share on other sites

To put it in everyday terms.. when you iterate through an array with foreach by default php uses a copy of the keys and values of the array. So if you were for instance to do this:

 

$array = array(1,2,3);
foreach($array as $val) {
  $val++;
}
print_r($array);
All you are doing is incrementing a temporary value within the scope of the loop. It doesn't actually change $array, because $var is just a temp variable that is a copy of the value of the current index. So, print_r will still show $array as (1,2,3). However, if you include the & prefix, it tells php to reference (use) the actual array instead of the temp copy. So if you do this:

$array = array(1,2,3);
foreach($array as &$val) {
  $val++;
}
print_r($array);
print_r will now show $array as (2,3,4)

 

On a sidenote, iterating through an array like this is basically the equivalent of using array_map or array_walk

 

 

 

above was just a example....  I am using session to store these array.

 

Thanks 

Link to comment
https://forums.phpfreaks.com/topic/286195-foreach-loop/#findComment-1468907
Share on other sites

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.