What is the reason for this IF/ELSE assignment?

Asked

Viewed 212 times

6

Because in this code the value 0 is assigned to the IF and the value 1 is assigned to the 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>";
    }
}

Taking into account the answers presented, then it is the opposite:

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

3 answers

11


In several languages (Javascript and C are also like this), it is common that the 0 is treated as equivalent to false in flow deviations (IF). This is for design.

In the specific case of PHP, an exopressure conversion occurs within the parentheses of IF to a boolean value. The following expressions turn false when converted:

  • the boolean FALSE itself;
  • integer 0 (zero);
  • floating point 0.0 (zero);
  • empty string ("");
  • the string "0";
  • an array without elements;
  • an object without member elements (only PHP 4);
  • the special NULL type (including variables not defined);
  • the Simplexml object created from empty tags;

I stole this information from official documentation.

  • 1

    Very booooommm !!! Thank you very much !!!

  • 2

    +1 by the link hehe was looking for him.

  • 2

    Note that this type of test can become extremely difficult to debug. Never trust cast PHP automatic. Most of the time he’s dumb and nosy. If your test serves to run something when something else succeeds, then prefer if( $something !== FALSE ) (note the comparison operator also by type).

6

php automatically cast some values like: zero, vazio and null are converted into false soon falls into Else, any other value ex: 1, -1 are interpreted as true

  • Perfect ... Great and enlightening your answer.

2

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

So if it is passed to the IF the value of 0(zero) is evaluated as false and the program executes the block defined in the ELSE, that is 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.

Totally how one expects the code to behave, not as stated in the question.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.