Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Nested foreach in PHP produces different results than I expect

Tags:

foreach

php

I'm having problems to iterate twice on the same array:

<? $indice=0 ?>
<?php foreach ($comisiones as $comision1):?>  
  <tr>  
    <td><?php echo ++$indice ?></td>  
    <td><?php echo tag('select',array('name'=>'comision_'.$indice),true)?>  
          <?php foreach ($comisiones as $comision2):?>  
            <option value="<?php echo $comision2->getId()?>">
               <?php echo $comision2->getNombre()." - ".$comision2->getDescripcion()?> 
            </option>
          <?php endforeach?> 
        </select>
    </td>
  </tr>
<?php endforeach?>  

The above code prints:

code result

And I'm expecting to see something like this (labels of the combos in the images are not the same, but I think the idea is clear):

expected results

Thanks in advance

like image 800
Neuquino Avatar asked Mar 28 '10 14:03

Neuquino


2 Answers

My first instict is don't use foreach loops. I believe that PHP is using some internal pointers so the two foreach loops affect each other's position. Instead use a normal for loop.

like image 156
Richard JP Le Guen Avatar answered Sep 19 '22 19:09

Richard JP Le Guen


Based on your code it seems like you don't actually want a foreach loop in the outher loop. Just do a regular for loop from 0 to the size of the array. Something like this:

for ($i = 0; $i < count($comisiones); ++$i) {
    // Do what you want
}
like image 42
alexanderblom Avatar answered Sep 19 '22 19:09

alexanderblom