bitwise operators

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
Lookie23
Forum Newbie
Posts: 7
Joined: Fri Jan 10, 2003 5:43 am

bitwise operators

Post by Lookie23 »

Hi!

I'm just beginning to work in php, and i have a question about a few lines of code:

$bgcolor = ($i++ & 1) ? $bgcolor1 : $bgcolor2;

echo '<tr>';
echo '<td bgcolor=”' . $bgcolor . '">'


Can someone briefly explain me how bitwise part of the expression in the tenary operator works? Thank for any help or hints.
User avatar
volka
DevNet Evangelist
Posts: 8391
Joined: Tue May 07, 2002 9:48 am
Location: Berlin, ger

Post by volka »

a short description can be found at http://www.php.net/manual/en/language.o ... hp#AEN4733

first it checks wether ($i & 1) is true or false (i.e. checking wether the lowest bit is set in $i, an even/odd test)
then $i is incremented
if the previous comaparison evaluated to true (1-bit was set -> $i was odd) $bgcolor1 will be assigned
$bgcolor2 otherwise.

almost the same as

Code: Select all

function is_odd($number)
{
	return ($number & 1);
}

if (is_odd($i))
	$bgcolor = $bgcolor1;
else
	$bgcolor = $bgcolor2; 
$i = $i + 1;
Post Reply