North Yorkshire, UK Kent, UK Chamonix, France Phone: 01905 570 270 Email: mint@createdbymint.co.uk

Tag Archives: selectors


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; }
php Leave a comment

Question? Give us a call.

Intelligent solutions for your online property be it simple or complex, just starting out or established. Get in touch with us, we'd love to help. Phone: 01905 570 270

Join our mailing list

We'll send you only occasional emails to share our latest ideas and offers with you.
So why not join up?

Interested in what we do?

Interested in what we do?

Get in touch

Contact Us