In some cases, PHP will convert numerical data (such as string containing numbers, etc.) into numerical processing, == operator is one of them. When using the == operator to loosely compare two strings, PHP will convert the numerical string into a numerical value for comparison. The following experiment confirms this conclusion:
<?php var_dump('01' == 1); ?>
The output result of the above code is : bool(true)
Therefore, when comparing strings, it is recommended to use the === operator to strictly check the string, or use functions such as strcmp() , thereby avoiding possible problems.
In addition, the commonly used in_array() function also has weak type problems, see the following code:
<?php var_dump(in_array('01', array('1'))); ?>
The output result of the above code is: bool(true)
I believe that PHP programmers who have used this function to perform security checks know what kind of security problems this will cause, right? Fortunately, the in_array() function provides us with a third parameter. Setting it to true can turn on the mandatory type checking mechanism of the in_array() function, as shown in the following code:
<?php var_dump(in_array('01', array('1'), true)); ?>
The output result is : bool(false)
Since PHP is a weakly typed language, that is to say, the concept of data type is weakened in PHP. Therefore, if you ignore the data type too much when programming (which is also a common problem among most PHP programmers), some problems will occur and even lead to security vulnerabilities. Finally, as the annoying saying goes, strictly check and filter external data.
Side effects
$a = '212345678912000005'; $b = '212345678912000001'; var_dump($a == $b);
The output of this code is bool(true), indicating that this judgment will conclude that the two are equal. Similar characteristics are in The third parameter of the in_array() function is false or not set. The reason is to first determine whether the string is a number, then convert it to long or double (C language data type) and then determine - use zendi_smart_strcmp. However, the comments in the source code say that the statement considers overflow situations
} else if (dval1 == dval2 && !zend_finite(dval1)) { /* Both values overflowed and have the same sign, * so a numeric comparison would be inaccurate */ goto string_cmp; }
dval1 and dval2 are the values of two strings converted to double types respectively. But why is this still the case?
Solution, use Three equal signs "===" replace two equal signs "==", and the in_array() function sets the third parameter to true: in_array('val', $array, true).
The above is the detailed content of Detailed explanation of PHP's == operator string comparison usage and its side effects examples. For more information, please follow other related articles on the PHP Chinese website!