Tutorial – Using Binary to Alternate Class/ID Names

In this tutorial I will show you how to use a PHP check to test weather or not a number is odd or even. This will then be used to load different class/ID names so that different CSS can be applied. This is a great tool to alternate code that is being run through a loop, for example WordPress posts on the main page.

Here’s all the code that is needed:




		
>

Now the first thing you’ll notice is I have the code separated into 2 parts. The reason for this is because the code will have to exist in 2 different parts.

This will set the default value for $i. It needs to go outside of your loop because if you were to put it into the loop you’d always reset the value.

Now lets look at the rest of the code that will inside of your loop:


		
>

The first thing we’re doing is incrementing $i by one number, this will go up every time this is triggered by the loop. Lets say your loop runs 3 times then $i will go like this: 0 > 1 > 2 > 3.

Now the next line of code is comparing $i to 1 and then will give the div the class name based on weather or not the match is true. Now you’re probably thinking it will only work when $i is 1 but what it is doing is comparing the match in binary. Here’s what some of the numbers look like in binary:

0 = 00000000
1 = 00000001
2 = 00000010
3 = 00000011
4 = 00000100

what “$i & 1” is actually looking for is if the 2 numbers in binary form ever have a matching number. So for 0 > 1 > 2 > 3 it would actually look like this:
0 & 1:
00000000
00000001
———-
No match

1 & 1:
00000001
00000001
———-
Match on last digit

2 & 1:
00000010
00000001
———-
No match

3 & 1:
00000011
00000001
———-
Match on last digit

So that is how it knows which number is odd and which one is even. And that is how you can make alternating class/ID names with PHP.

Leave a Reply