# how does this work

#### Do you have a question? Post it now! No Registration Necessary.  Now with pictures!

•  Subject
• Author
• Posted on
Hi Folk

I came accross this very simple function, but I have no idea how it works
(the ampersands).  Can you explain it.

function is_even(\$num){
return (is_numeric(\$num)&(!(\$num&1)));
}

TIA

Nicolaas

## Re: how does this work

Heh, nice solution! :)

The 1st statement checks, if \$num is a number.

The 2nd one checks, if the the binary "one" is set, as it is with every
odd number.
Alternatively, you could use modulo:
!(\$num % 2)

statements; I would use "&&" or "and" here. ;)

Cheers..

## Re: how does this work

milahu wrote:

Why would you do that? '&&' and '&' are completely different operators,
and give different results when evaluated in boolean context on two numbers.

Tim

## Re: how does this work

Tim Martin wrote:

Because I prefer comparing boolean values with logical instead of byte
operators.

## Re: how does this work

milahu wrote:

Sorry, I misread you. I thought you were referring to replacing the
second '&', not the first one. I didn't even spot that the two boolean
expressions were being combined with a bitwise operator (which I agree
is wrong).

For reference, the function in question was:

function is_even(\$num){
return (is_numeric(\$num)&(!(\$num&1)));
}

Tim

## Re: how does this work

On Fri, 21 Apr 2006 11:20:27 +0100, Tim Martin wrote:

Why is it wrong? you're anding 0 or 1 with 0 or 1, and that'll return 1
only if both are 1.  It might even be faster - probably not though.

## Re: how does this work

Steve wrote:

It's wrong in the sense of being a bad habit, not in the sense of
returning the wrong result. Doing this sort of thing regularly can lead
to brittle code that breaks due to seemingly innocuous changes.

Tim

## Re: how does this work

windandwaves wrote:
Thanks folk

It makes more sense now.  I gather that the single ampersand test for a
particular bit in a byte, while the double ampersand is the AND operator.

Thanks a million.

Nicolaas