views:

820

answers:

2

I am using php/codeigniter, and typically to loop over query results I would do something like this:

<?php foreach($data as $row):?>
//html goes here
<?php endforeach;?>

But, say I have another object array, $data2, with the same number of objects as $data: is there any valid php syntax that would allow me to simultaneously access "rows" on both objects within the same loop using the foreach statement. I know I could do this with a regular for loop by accessing the indeces of the arrays..but this wouldn't be as clean.

+1  A: 

I think the indices are your best bet. This would be a strange language feature because in general you don't know that two arrays have the same size and what do you do when one runs out before the other?

Maybe you could refactor the code such that instead of $data and the $other array, you had a single array whose entries were an associative array with a ->data and ->other members. But that should only be done if it makes sense in the data model. IMHO, looping over the index in this case is fine.

Mike Kale
+3  A: 

You could to something like this:

<?php foreach($data as $key => $row): $row2 = $data2[$key]; ?>
//html goes here
<?php endforeach;?>

Which would effectively enable you to loop both arrays at the same time.

Andrew Moore
THANK YOU! exactly what I needed
es11