Why does if($flip) work?


#1


https://www.codecademy.com/courses/web-beginner-en-5YvPF/0/5?curriculum_id=5124ef4c78d510dd89003eb8


Just wondering why the statement if($flip) executes the heads code. Is it just because $flip doesn't equal 0?


$flip = rand(0,1);
		$flipCount ++;
		if ($flip){
			echo "<div class=\"coin\">H</div>";
		}
		else {
			echo "<div class=\"coin\">T</div>";
		}


#2

Pretty much. When 0 is returned, that can also be read as false. When 1 is returned, that can also be read as true.

So, in this particular case, $flip = rand (0,1) is a clever way of assigning a random value of true or false to the variable $flip.

// pseudocode
$flip = rand(false, true);

Since the rand function only takes in integers, then 0 and 1 as min-maxes are a great way to go about testing if the coin was flipped or not! Or, if it's head or tails.


#3

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.