September 30, 2010 in PHP, Tutorials by admin

Have you ever had a online store, photo gallery, large list etc. that you wanted an easy way to tell php to start a new row of entries. For example you have 20 photos but only want 4 photos per line?
There is a really easy way to do this using the php modulus (%) operator.

In this example we will use a for loop to count to 20 and through each loop we will check if $i%4 equals zero. If it does we will echo out a break tag. You can substitute 4 with how many items you want per row.

1
2
3
4
5
6
7
8
9
10
11
for($i = 1; $i <= 20; $i++){
	echo $i." ";
	if(($i%4) == 0){
		echo "<br />";
	}
}

If you run this code it should output:

1 2 3 4
5 6 7 8
9 10 11 12
13 14 15 16
17 18 19 20

You can see how this can be easily used when pulling information from a database, plain text, or just running loops. For image galleries you would just replace $i with your image code, for shopping cart items, etc. Try it out for yourself and you can save yourself a lot of time!