phpeveryday.com

The best tutorial of php, php framework, php strategies, object oriented oriented,


PHP - Number: Testing for Odd or Even Numbers

Tag: number, odd number, even number   Category: PHP Basic
post: 16 Mar 2008 read: 140


PHP Number Tips - Part 8:If you want to find out if a number is odd or even, you can use PHP's bitwise & operator such as:

<?php
//define number
$num = 31;

//see if number is odd or even
//result: "Number is odd"
echo (1&$num) ? "Number is odd" : "Number is even";↵
?>

For the odd numbers, it expressed in binary format and the least significant digit is always 1, whereas for even numbers, it is always 0. If you don't fully understand the listing above, you can take a look at http://www.gamedev.net/reference/articles/article1563.asp for a tutorial on bitwise manipulation. More than that, you can consider a different test which involves dividing the number by 2 and checking the number alternatively (with the even numbers, the remainder will be zero). Beneath, this alternative is illustrated as follows:


<?php
//define number
$num = 10;

//see if number mod 2 returns a remainder
//result: "Number is even"
echo ($num % 2) ? "Number is odd" : "Number is even";
?>



| Give Your Opinion | Recommend
Share and Bookmark to: These icons link to social bookmarking sites where readers can share and discover new web pages.
digg del.icio.us technorati Ma.gnolia BlinkList

Recommended articles by other readers:
Web Services: How PHP Kiss VB.NET? (Part 1)
Chart: How to Build Cool Animation Real Time Chart
Joomla: Fast Road to Understand Component Programming
Email: Send Attachement Mail
mod_rewrite - Part 1: create your "fantasy" URL

What do You Think?
Your Name *:
Email *:
(Will not be published)
Website/URL:
Your Comment *:
* Required


615
posting