Looping images into table for gallery?

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
bradles
Forum Commoner
Posts: 89
Joined: Wed Jun 30, 2004 10:40 pm

Looping images into table for gallery?

Post by bradles »

Hi All,

Does anyone know a good way of looping 12 images into a table that is 3 columns x 4 rows?

I was thinking of setting up an outer loop for the rows and an inner loop for the columns. Something like:

Code: Select all

echo "<table>\n";
	//Row Setup
	for ( $y = 1; $y <=4; $y++ ) {
		echo "	<tr>\n";
		
		//Column Setup
		for ( $x = 1; $x <=3; $x++ ) {
			echo "<td>\n";
			//Image gets put here
			echo "</td>\n";	
		}
		
		echo "	</tr>\n";
	}
echo "</table>\n";
This looks like it could get pretty messy. Is there an easier way out there of doing this?

Brad.
peni
Forum Commoner
Posts: 34
Joined: Thu Nov 18, 2004 1:15 pm

Post by peni »

no, as long as you keep your code clean and understandable, this is a good solution. you can put the inner for() into an extern function and call it, but it's not necessary, due to the fact that you can quickly vary the rows/cols count this way.
timvw
DevNet Master
Posts: 4897
Joined: Mon Jan 19, 2004 11:11 pm
Location: Leuven, Belgium

Post by timvw »

Now all that you need to do is make it a little more flexible (so you can reuse it)

Code: Select all

/*
 * make HTML to display images
 *
 * @param $images an array with assoc arrays that have keys src and alt
 * @param $rows the number of rows
 * @param $cols the number of columns
 * @return the generated HTML
*/

function makeGallery($images, $rows, $cols)
{
  $html = '';
  for ($i = 0; $i < $rows; ++$i)
  {
    $html .= '<tr>';
    for ($j = $j < $cols; ++$j)
    {
      $html .= '<td><img src="{$images[(($i * $cols) + $j)]['src'}" alt="{$images['(($i * $cols) + $j)]['alt']" /></td>';
      }
    $html .= '</tr>';
  }
  return $thml;
}
User avatar
pickle
Briney Mod
Posts: 6445
Joined: Mon Jan 19, 2004 6:11 pm
Location: 53.01N x 112.48W
Contact:

Post by pickle »

You can do it with only 1 loop:

Code: Select all

$number_of_images = 12;
$images_per_row = 4;
echo "<table><tr>";
for($col_counter = 1; $col_counter <= $number_of_images; ++$col_counter)
{

    //this is what breaks up your rows
   if($col_counter%$images_per_row == 0)
   {
     echo "</tr><tr>";
   }

    echo "<td>";
    //dump image here
    echo "</td>";
}
echo "</tr></table>";
Real programmers don't comment their code. If it was hard to write, it should be hard to understand.
Post Reply