views:

31

answers:

3

Hi everybody,

I have the following php loop that takes an array that contains a set of arrays, then I convert each array to a list to manipulate more accurately the elements.

while ($i<sizeof($my_array)){
    while(list($key,$val) = each($my_array[$i])){
      $j = $i+1;
        if ($key == "fruit"){
          $val = "ananas".$j;
          echo $val;
        }
     } 
 $i++;
 }

But, when I print the "search" array (print_r($my_array)), the values don't change. How can you explain thaht? Is there a solution to modify the "$val" without changing the loop structure and logic?

Thank you,

Regards.

+3  A: 

Use foreach with reference:

$i = 0;
foreach ( $my_array as $key => &$val ) {
    ++$i;
    if ($key == "fruit"){
        $val = "ananas" . $i;
        echo $val;
    }
}
hsz
+1  A: 

$val is a copy of the data contained in $my_array[$i], not the actual data. To change the data in the array:

while ($i<sizeof($my_array)){ 
    while(list($key,$val) = each($my_array[$i])){ 
      $j = $i+1; 
        if ($key == "fruit"){ 
          $my_array[$i][$key] = "ananas"; 
          echo $my_array[$i][$key]; 
        } 
     }  
 $i++; 
 } 

And it's probably easier to use a foreach loop

Mark Baker
A: 

each() doesn't pass the data as references, without modifying the loop that much:

    if ($key == "fruit"){
      $val = "ananas";
      echo $val;
      $my_array[$i][$key] = $val;
    }

Of course, there are better ways to do that. But you wanted an answer that didn't change the loop structure.

Tim Lytle