-1

This is the code

<p>We are going to flip a coin until we get three heads in a row!</p>

<?php
$headCount = 0;
$flipCount = 0;
while ($headCount < 3) {
    $flip = rand(0, 1);
    $flipCount ++;
    if ($flip) {
        $headCount ++;
        echo "<div class=\"coin\">H</div>";
    } else {
        $headCount = 0;
        echo "<div class=\"coin\">T</div>";
    }
}
echo "<p>It took {$flipCount} flips!</p>";
?>

I've played around with Java but I'm now learning PHP. The part that doesn't make sense right here is this.

if ($flip) {
    $headCount ++;
    echo "<div class=\"coin\">H</div>";
}

What exactly is being checked here? I doubt it's checking whether $flip is true.

1 Answers1

0

It's a common shorthand in these kinds of languages. Once you get used to it, it seems natural.

In this case,

if ($flip)

is equivalent to:

if ($flip == 1)

But PHP is really just checking for a "truthy" value: true, not zero, not "0" or "", not [], and others will evaluate as true and pass the if ($flip) test.