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

While Loops in PHP Forum

View Course » View Exercise

308 points
Afad0d72c146c33c5adbb9edf38f9f3d?s=140&d=retro
Submitted by
Ratnadeep Bhattacharjee
over 2 years ago

question about the $flip variable

I am new to programming so its kinda difficult to understand stuff right off the bat...I am hoping that someone will answer my question which is -- just like the $headCount and $flipCount variables were defined before the loop, why was the $flip variable not defined before the loop, how does PHP understand that it has to flip the coin? Are there some default words that PHP understands like the word flip...? Also could anyone please explain in simple words what the code means...

while ($headCount < 3) {
$flip = rand(0,1);
$flipCount ++;
if ($flip){
$headCount ++;
echo "H";
}
else {
$headCount = 0;
echo "T";
}


6 votes

permalink

I understand your question, because was mine too...

Variable $flip is defined when assigning a random value
$flip = rand(0,1); on your 2nd line.

then... the condition
if($flip)
is equal to
if($flip==1)

Why? Because in php if($var) is equal to say "if var is true". And if(!$var) is equal to say "if var is false". Now, we assigned two values to $flip (with rand function): 0 or 1; in php $flip=0 is the same that $flip is false, the same that !$flip; on the other hand, $flip=1 is the same that $flip is true, the same that $flip.
So the while condition - while($flip) - is satisfied when when $flip=1, if $flip=0 the while condition is over and the loop ends.

I hope it was enough understandable.
Bye.

288 points
565dd23986f5526de7000220_145937852
Submitted by
Daniele Cuder
over 2 years ago

2 Comments

Afad0d72c146c33c5adbb9edf38f9f3d?s=140&d=retro Ratnadeep Bhattacharjee over 2 years ago

Thank you so much Daniele...

Ff7f5591e3f60acac3214fe0703dcbae?s=140&d=retro jverbosk over 2 years ago

Thanks, this helped a lot!