Tag Archives: math
Detect Even Numbers using PHP
Using PHP Math
We can use standard PHP math to detect even numbersĀ in one simple line of code by using the modulus operator (%). Which gives the remainder left over after a division, for example 5 divided by 2 would equal 2.5. Therefore giving a quotient of 2 and a remainder of 1. Whereas 6 divided by 3 equals 2, with a quotient of 3 and a remainder of 0. So the conditional statement using the modulus of any number by 2 will yield a one and zero answer for odds and evens. In conclusion “any number % 2” will evaluate to zero if the given number is even, and one if the given number is odd. Which is useful for outputting different markup during a loop.
//the condition if ($number % 2 == 0) { //do something if even numbers } else { //do something if odd numbers }
CSS Alternative for formatting odd/even HTML markup
Although, if it’s just a case of trying to give some different formatting to an HTML table for example. It would be far simpler to just use the nth-child(odd)/nth-child(even) CSS pseudo selectors to target the odd and even items.
li:nth-child(even) { background-color:#eee; }
and
li:nth-child(odd) { background-color:#fff; }