This forum is now read-only. Please use our new forums at discuss.codecademy.com.

While Loops in PHP Forum

View Course » View Exercise

1725 points
Picture
Submitted by
Paul Bentham
over 4 years ago

if($flip)... Why does this work as a Boolean?

This has me a little bit puzzled? shouldn't it be if ($flip == 1)?

I appreciate that the answer is either 1 or 0 but if $flip is the 1 or True, what is False?


0 votes

permalink

0 equals false.

Any value different from 0 equals true.

729 points
B3d6f7681a76849f5c3f732a257e1e9e?s=140&d=retro
Submitted by
andre.mendes
over 4 years ago

4 Comments

Picture Sondre Em over 4 years ago

Sorry if I'm a bit slow, but I just want to confirm that I understand this right:

So, if I say "flip should be a random number, either 0 or 1".
(ie $flip = rand(0,1);)

And then say - if($flip); then do something, then if the random string generates a 0 then nothing happens, but if it generates a 1, then the "if"-statement goes through?

If it said "rand(0,9)" then 0 would not do the "if", but a 1, 2 [...] 9 would?
And if it said "rand(1,9)", follow by a if($flip); - that would be an infinite loop?

Picture Sondre Em over 4 years ago

(uch, my linespaces disappeared. sorry if the reply seems a bit cluttered)

B3d6f7681a76849f5c3f732a257e1e9e?s=140&d=retro andre.mendes over 4 years ago

If it said "rand(0,9)" then 0 would not do the "if", but a 1, 2 [...] 9 would?
Yes, that's true.

And if it said "rand(1,9)", follow by a if($flip); - that would be an infinite loop?
In this case no, because the condition for the loop is ($headCount < 3).
But you would always get three heads in three flips, because the condition ($flip) would always be true.

B3d6f7681a76849f5c3f732a257e1e9e?s=140&d=retro andre.mendes over 4 years ago

Same problem with line breaks. Hope you get it...


0 votes

permalink

Thank you! Wow I was trying to figure this out. And now I understand, the random isn't a value, it is there to tell us whether a condition is true or false.

1135 points
507881b977dfae0200001827_621514356
Submitted by
AmmyKami83
over 4 years ago