Page 1 of 1

Operator Quiz

Posted: Fri Aug 11, 2006 4:34 pm
by Ollie Saunders

Code: Select all

if ($a = 1 && 1) {
    var_dump($a);
}
if ($a = 1 and 1) {
    var_dump($a);
}

if ($a = 1 || 1) {
    var_dump($a);
}
if ($a = 1 or 1) {
    var_dump($a);
}

Posted: Fri Aug 11, 2006 4:51 pm
by feyd
fun with precedence. weeeeee

Image

Posted: Fri Aug 11, 2006 4:57 pm
by Ollie Saunders
Yep, don't give the game away now.

Posted: Fri Aug 11, 2006 5:56 pm
by Benjamin
I voted int(1) bool(true) int(1) bool(true), number 3, based on something I remember reading in the PHP manual a long time ago.

Posted: Fri Aug 11, 2006 5:58 pm
by Ollie Saunders
Few more votes and I will reveal

Posted: Fri Aug 11, 2006 7:38 pm
by matt1019
I voted:

bool(true) int(1) bool(true) int(1)

Shouldn't this be the case/output?

cant wait to see the results.

-Matt

Posted: Fri Aug 11, 2006 7:54 pm
by Ollie Saunders
OK well congratulatous on all those who voted "bool(true) int(1) bool(true) int(1)" you are correct!
I'm surprised nobody voted for either of the first two. Until just now I thought that "and" and "&&" and "or" and "||" were identical. (That was one hell of a sentence).

Anyway here's the explaination.
This behaviour is to do with something called operator presendence. Operator presendence is simply what order things are done in.

"and" has a lower precedence than "=" (assignment)
while "&&" has a higher precedence than "=".

This means that when appearing in a single expression the opperands on either side of an "&&" operator are evaluated using that operator before the opperands on either side of an "=" operator are. With "and" the opposite is true.

To make this clearer, these are functionally equivalent i.e. the bracket have no effect:

Code: Select all

$result = $a = (1 && 1)
$result = $a =  1 && 1
and

Code: Select all

$result = ($a = 1) and 1
$result =  $a = 1  and 1
$result is always true.

Posted: Fri Aug 11, 2006 10:24 pm
by matt1019
Yay for me!! (and of course the rest of 3 people who got it right) jk... jk

nice one ole!

-Matt

Posted: Fri Aug 11, 2006 10:27 pm
by Benjamin
I knew it was the third or fourth option because I remember reading that the precendence was different. I just guessed though.

Posted: Sat Aug 12, 2006 12:46 am
by RobertGonzalez
Ha! I totally cheated and waited for the answer. Well not really... I picked this thread after the answer was revealed. But I got it right! Yay!

Posted: Sat Aug 12, 2006 1:06 am
by matthijs
And I was thinking 1 && 1 = 2 8O :? :wink:

Posted: Sat Aug 12, 2006 2:49 am
by pureDesi
matthijs wrote:And I was thinking 1 && 1 = 2 8O :? :wink:
lol, I so wish it were that simple :/

Posted: Sat Aug 12, 2006 3:23 am
by Benjamin
You'd think 1 && 1 would = 3. 1 and and 1 = 3.