Home > Net >  Why is it always returning the first statement of the if/ifelse/else statement?
Why is it always returning the first statement of the if/ifelse/else statement?

Time:01-06

<?php
     $type = rand(0,1).PHP_EOL;
     echo $type;
     if ($type == 0) {
          include_once 'include/types of lections/type1.php';
     } elseif ($type == 1) {
          include_once 'include/types of lections/type2.php';
     } else {
          include_once 'include/types of lections/type3.php';
     }
?>

I wanted to randomly include three different types of lections. With the code I'm using the echo $type; is random (0 or 1), but it includes always type1.php. Thanks for your help.

CodePudding user response:

There is a couple of problems with your code:

1.rand(0,1) will always return either 0 or 1, so $type will always be either 0 or 1, and the else block will never be executed.

2. You are using == to compare $type to the integer values 0 and 1. This is not wrong, but it is more common to use === to compare both the value and the type of a variable. In this case, $type is a string because it is concatenated with PHP_EOL, so using === would make the comparison more accurate.

3. You are using include_once to include the files. This will include the file only if it has not been included before. If you want to include the file every time, you should use include instead.

  • Related