views:

45

answers:

2

Why is it that this code prints "Hello!" four times and then prints "1":

<?php
for ($i=1 AND $blah=1; $i<5; $i++) echo("Hello!");
echo($blah);
?>

While this doesn't print out "Hello!" at all and then prints "1":

<?php
for ($i=1 && $blah=1; $i<5; $i++) echo("Hello!");
echo($blah);
?>

I know AND and && have different precedences, but that doesn't seem to apply here. What am I missing? (I'm using a variant of the code above, since I will use $blah within the for loop, and I want to set the value for it). Thanks for any help!

+1  A: 

I doubt that either the AND or && are what you're looking for here. If you want to execute both $i=1 and $blah=1 in the initialization expression, you need to separate them with a comma:

for ($i=1, $blah=1; $i<5; $i++) echo("Hello!");
Kaleb Brasee
Oh, thanks. That makes more sense than trying to use and.
Peter Ajtai
+3  A: 

@OP, please read this doc. It explains the difference under Example #1 logical operators

ghostdog74
That's what I was missing! Thanks. I still have to mull over that first example to truly get what is meant by, "those operators are short-circuit."
Peter Ajtai