Click to See Complete Forum and Search --> : [RESOLVED] for each help
EJMAES1973
03-05-2008, 09:23 PM
Hey, I have a script to display images in an ordered list and then styled to make it look nice. The only problem is that this uses the css property float and I am just using div tags so it messes that up. I was wondering how I would go about creating a foreach statement to create a table 4 columns wide? If I am not being clear just let me know and I will try to explain. Thanks for any help.
ss1289
03-05-2008, 11:10 PM
I'm not sure if I understand right but you could wrap each element in the foreach loop with <td> tags.
EJMAES1973
03-05-2008, 11:14 PM
Right, that is pretty much what I am wanting to do, but I also only want 4 images per row and that is the part I don't know how to add to the foreach loop
tfk11
03-05-2008, 11:30 PM
You'll need two loops for that.
//$items = your array of items
$num_cols = 4;
echo '<table>';
for( $i = 0, $max = count($items) / $num_cols; $i < $max; ++$i ) {
echo '<tr>';
for( $i2 = 0; $i2 < $num_cols; ++$i2 ) {
$current_item = $i * $num_cols + $i2;
if( isset($items[$current_item]) ) {
echo '<td>', $items[$current_item], '</td>';
} else {
echo '<td> </td>';
}
}
echo '</tr>';
}
echo '</table>';
Note that the code above is untested but hopefully it helps.
ss1289
03-05-2008, 11:33 PM
Right, that is pretty much what I am wanting to do, but I also only want 4 images per row and that is the part I don't know how to add to the foreach loop
so you only want to go through the foreach loop 4 times?
Use a counter, check when it reached 4, then use "break;" to break out of the loop.
EJMAES1973
03-09-2008, 04:33 AM
Note that the code above is untested but hopefully it helps.
It worked no worries. I'm surprised it did though. Not because of your code, but because I combined two different sets of code and I know pretty much nothing about for statements. Thank you so much for the help. Does anyone know a good place to learn about for statements?
tfk11
03-10-2008, 08:36 PM
Glad the code helped.
Everything you need to know about for statements can be found in the php manual under control structures.
EJMAES1973
03-10-2008, 08:39 PM
alright thanx. I was able to understand that code enough to use it for other things so I think I am getting the hang of it. Thanx again