What is the reason for this IF / ELSE assignment?

6

Because in this code the 0 is assigned to IF and the 1 value is assigned to ELSE ?

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

Considering the answers given, then the opposite is true:

  

IF = TRUE (1) and ELSE = FALSE (0)

    
asked by anonymous 01.10.2014 / 18:48

3 answers

11

In many languages (Javascript and C are also so), it is common for numeric%% to be treated as equivalent to false in flow variances (% with%). This is by design.

In the specific case of PHP, there is a conversion of the expression within the parentheses of 0 to a boolean value. The following expressions were rendered false when converted:

  • the Boolean itself FALSE;
  • the integer 0 (zero);
  • floating point 0.0 (zero);
  • empty string ("");
  • string "0";
  • an array with no elements;
  • an object without member elements (PHP 4 only);
  • special type NULL (including undefined variables);
  • the SimpleXML object created from empty tags;

I've stolen this information from official documentation . p>     

01.10.2014 / 18:54
6
php automatically cast some values such as: zero , vazio and null are converted to false soon falls into else, any other value ex: 1 , -1 are interpreted as true

    
01.10.2014 / 18:54
2

The value 0 is not assigned to the IF. The IF only evaluates whether the passed parameter is true or false and to make this evaluation uses the criteria explained above.

Then if passed to the IF the value of 0 (zero) is evaluated as false and the program executes the block defined in ELSE, ie the parameter in the IF is not true.

If the value is 1, which is evaluated as true, then the block within the IF is executed.

As expected the code behaves, not as stated in the question.

    
01.10.2014 / 20:40