Jump to content

PHP codeacademy problem ( do/while )


kuba2
 Share

Recommended Posts

Hello

I am learning PHP and made a codeacademy PHP online course. Basic stuff and interesting course for free.

But there is a do/while exercise I can't get my head around:

 

 

In the following, there is a flipcoin example, which flips, as long the result is head.

In the do statement there is the if and the else 

The if condition is $flip and it echoes a H letter for Head. The else echoes a T for Tail.

$flip is random 0 or 1

My question:

How can the if and else statements be H or T if $flip is random? I don't understand the $flip variable, because in my head it can be 0 or 1.....therefor if is not one fixed value, because of the rand(0,1) it can change

How does the programm to put out a H or a T?

I hope my question is clear enough

 

 

Thanks for any clarification

Jakob

<!DOCTYPE html>
<html>
    <head>
    	<link type='text/css' rel='stylesheet' href='style.css'/>
		<title>More Coin Flips</title>
	</head>
	<body>
	<p>We will keep flipping a coin as long as the result is heads!</p>
	
	
	<?php
	$flipCount = 0;
	do {
		$flip = rand(0,1);
		$flipCount ++;
		if ($flip){
			echo "<div class=\"coin\">H</div>";
		}
		else {
			echo "<div class=\"coin\">T</div>";
		}
	} while ($flip);
	$verb = "were";
	$last = "flips";
	if ($flipCount == 1) {
		$verb = "was";
		$last = "flip";
	}
	echo "<p>There {$verb} {$flipCount} {$last}!</p>";
	?>
	
	
    </body>
</html>

 

Link to comment
Share on other sites

if($flip) {
  echo "H"
}

You are exactly right, I think you just miss a thought:

The condition relates to the value of $flip. The value is either 0 or 1. And in PHP, 1 in a condition is “like” true, and 0 is “like” false.

So $flip may be 1. In that case PHP will coerce it to true and finally print H because the condition is met.
If $flip is 0, PHP will coerce that to false and print T because the condition for the if() was not met. So the else block is executed.

Hope that helps?

  • Like 7
Link to comment
Share on other sites

Just wanted to add that it's not just PHP that treats 0 as False and 1 as True. 
You'll find most (traditional) languages will do the same (at least the ones I've come across).

There are some exceptions like Ruby & Lisp which treats 0 as true,  AFAIK.

If you're wondering why 0s & 1s ... well I don't have a definite answer myself as it's one of those topics that will divide opinion.
IMHO I side with the view that it originates from Electronics & Boolean Algebra.
But it certainly sounds like a question for Quora :)

  • Like 3
Link to comment
Share on other sites

 Share

×
×
  • Create New...