PHP string comparison operation changes in

Due to the weak nature of the type of PHP, you can do some strange things, some of them good, some of them will make you fall into the pit inside. such as:

 echo '1' + 5;

 

In some languages, which may cause the program to crash, but PHP will attempt to calculate any string to an integer. In this case, it will convert the string to an integer of 1 to 5 and added to generate 6.

By the way, if you do this in JavaScript, then you will find the opposite result. Because the connection with the same character add character, if any current value is a string, JavaScript will always try to truncate the value. So the result in JavaScript will be "15."

If we change the string to the string "one" and then perform the same operation, the result is 5.

echo 'one' + 5;

 

This is because if PHP can not convert a string to an integer, it is assumed to 0.

 

We can compare it elevate to another level. View PHP type comparison tables, you can see there are two different ways to compare two values.

Consider the following code snippet. We look forward to what the outcome will be?

 

  1. $a = 'string' ;
  2. $b = 0 ;
  3.  
  4. if ( $a == true && $b == false && $a == $b ) {
  5. exit ;
  6. }

那么答案是程序会退出,因为所有这些比较都是正确的。

'a string'== true等于true,因为如果与布尔值进行比较,PHP会将任何非空字符串计算为true。

0 == false等于true,因为与布尔值比较时,整数0被计算为false。

'a string'== 0也计算为true,因为与整数相比,任何字符串都会转换为整数。如果PHP无法正确转换字符串,则将其计算为0.因此0等于0,等于为真。

要解决此问题,您可以使用===运算符代替==运算符。此运算符(也称为三重等于运算符)仅在两个值具有相同值时才会求值为true,如果它们是相同类型,则仅计算为true 。因此,如果我们将示例更改为使用三等于运算符,则所有项都将计算为false。这是因为字符串不能是布尔值,整数不能是布尔值,字符串不等于整数。

两个等于运算符之间的差异很重要。每个都有它自己的用途,但如果你对你的价值类型有任何疑问,那么使用三等于运算符,特别是当通过测试会给你的程序带来灾难。

When using the strpos () function and the like, triple equals operator is indispensable. This is because it returns false if the string is not found. The following example $ position variable is equal to false.

$position = strpos('abcd','z');

But if the string is found at position 0 what happens? If you use two equal operator, you will find that your position will be equal to false.

if (false !== strpos('abcd','a')) {
echo 'found';
} else {
echo 'not found';
}

 

Guess you like

Origin www.cnblogs.com/baocheng/p/11454156.html