When a variable is 0 in PHP, the variable is also "equal" to false. So how to distinguish between 0 and false? This is very useful in some conditional statements, as this article will illustrate.
Look at the code first:
The function of this code is to find whether a string begins with a certain word
The code is as follows | Copy code | ||||||||||||||||
$keyword = "you";
if(strpos($title , $keyword ) == 0) {
} else {
|
The code is as follows | Copy code |
if(strpos($title , $keyword ) == 0) { echo "correct"; } else if(strpos($title , $keyword ) == false) { echo "Error"; } Output: Correct |
The code is as follows | Copy code |
if(strpos($title , $keyword ) === 0) { echo "correct"; } else if(strpos($title , $keyword ) === false) { echo "Error"; } Output: Error |
The code is as follows | Copy code |
/* * Test boolean * 0 false */ $num = 0; $bTest1 = false; $bTest2 = true; $strTest2 = 'false'; if($num == $bTest1) { echo ('The numbers 0 and false can be equal');//Display echo (" "); } if($bTest1) { echo('Never executed ');//Does not display } if(1) { echo('Will it be executed? ');//Execute } if($bTest2) { echo('I am the boss and I want to execute ');//Execute } else{ echo('Everything you don’t want is mine '); } echo (false == 0);//Display 1 to indicate equality echo (true == 1);//Display 1 to indicate equality function testReturn () { echo('aaaaa'); return; return 'bbbb'; echo('cccc'); } //return means that the return of this function means that everything below will not be executed, and exit means to exit the program echo testReturn();//Calling this function will output ‘aaaa’ ‘bbbbb’ ?> |
Many times false is also equal to 0. When the value we want to return contains 0, for example, we should pay attention to the query of numbers. You can use === to determine whether they are completely equal,
PHP has a gettype() function to get the type of a variable. You can use the === operator (look, there are three equal signs). The difference from the == operator is that this operator compares both the value and type of the data.
When different variable types are involved in the termination condition, it is important to perform strong type checking by using the === and !== operators.