arrays - What is & in the php foreach statement? -


this question has answer here:

in order able directly modify array elements within loop precede $value &. in case value assigned reference http://php.net/manual/en/control-structures.foreach.php.

 $arr = array(1, 2, 3, 4);   foreach ($arr &$value) {     echo $value;   }   $arr = array(1, 2, 3, 4);  foreach ($arr $value) {    echo $value;  } 

in both cases, outputs 1234. adding & $value do? appreciated. thanks!

in beginning when learning passing reference isn't obvious....

here's example hope hope clearer understanding on difference on passing value , passing reference is...

<?php $money = array(1, 2, 3, 4);  //example array moneymaker($money); //execute function moneymaker , pass $money-array reference //array $money 2,3,4,5 (because $money passed reference).  eatmymoney($money); //execute function eatmymoney , pass $money-array value //array $money not affected (because $money sent function eatmymoeny , nothing returned). //so array $money still 2,3,4,5  echo print_r($money,true); //array ( [0] => 2 [1] => 3 [2] => 4 [3] => 5 )   //$item passed value foreach($money $item) {     $item = 4;  //would set value 4 variable $item } echo print_r($money,true); //array ( [0] => 2 [1] => 3 [2] => 4 [3] => 5 )   //$item passed reference foreach($money &$item) {     $item = 4;  //would give $item (current element in array)value 4 (because item passed reference in foreach-loop) }  echo print_r($money,true); //array ( [0] => 4 [1] => 4 [2] => 4 [3] => 4 )   function moneymaker(&$money) {        //$money-array passed function reference. //any changes $money-array affected outside of function   foreach ($money $key=>$item) {     $money[$key]++; //add each array element in money array 1   } }  function eatmymoney($money) { //not passed reference. values of array sent function   foreach ($money $key=>$item) {     $money[$key]--; //delete 1 each element in array $money   }   //the $money-array inside of function returns 1,2,3,4   //function isn't returing } ?> 

Comments

Popular posts from this blog

linux - xterm copying to CLIPBOARD using copy-selection causes automatic updating of CLIPBOARD upon mouse selection -

c++ - qgraphicsview horizontal scrolling always has a vertical delta -