Home >Backend Development >PHP Tutorial >Pitfalls 2 that PHP may encounter
Earlier we shared with you the pitfall 1 that PHP may fall into. In this article, we will share with you the pitfall 2 that PHP may fall into. We hope it can help everyone.
Some of the pitfalls I encountered in the actual development process of PHP were caused by my lack of understanding. When I got into the pit, I really burst into tears.
Regarding the comparison of integers and strings, I corrected this problem once for others, but in the end I didn’t want to fall into it myself. It was really embarrassing. I wrote it down to prevent it from happening again!
Let’s look at this example directly:
<?php $foo = 0; $bar = 'a3b4c5'; if ( $foo < $bar ) { echo 'output'; }
Will it happen? As for output, the answer is no, why? Because when a number is compared with a string, the string will be converted into a number. If you call the function that converts to an integer intval( $bar ), you will find that its value is 0, and naturally it will not It's greater than 0. If the value of $bar is '3a4b5c', then the result will be output, because the value of the string converted into a number is 3. For specific conversion rules, please refer to PHP Manual:
##http://us2.php.net/manual/zh/language.types.string.php#language.types.string.conversion
In fact, if $foo is initialized to '', there will be no error if two strings are compared.
Continuing with the pit, let’s look at another one:
if ( $foo == 'a1b2c3' ) { echo 'output'; }
Will it happen this time? What about being exported? The answer is yes, the reason is actually the same as above, 'a1b2c3' is implicitly type converted to 0 during comparison.
The solution to the above problem is simply to compare the two numbers with the same type without implicit type conversion. At this time, the congruent sign (===) comes into play. , because the three equal signs will not only compare values, but also types. In addition, when comparing strings, if you use the strcmp() function, this problem will not occur.
Another example:
$checkedKeys = array('someKey1', 'someKey2'); $arrTest = array('someKey1' => 'someValue', 'otherValue'); foreach ($arrTest as $key => $value) { if (in_array($key, $checkedKeys)) { echo "The key valid: $key \n"; } }Similarly, there will be two outputs here, the second time The output $key is 0, do you understand? The solution is to add the third parameter to the in_array() function and set it to true to perform strict type comparison. The document is here http://php.net/manual/zh/function.in-array.php
One of the great advantages of the php language is its flexibility, and this also brings hidden dangers to codes that are not written carefully and carefully.
The pit that PHP may fall into
The above is the detailed content of Pitfalls 2 that PHP may encounter. For more information, please follow other related articles on the PHP Chinese website!