Home >Backend Development >PHP Tutorial >Some common pitfalls when switching to PHP development_PHP Tutorial
1. strrchr function
The note on the W3School site is as follows:
Thestrrchr() function finds the last occurrence of a string within another string and returns all characters from that position to the end of the string.
If successful, return false otherwise.
Actually, this function searches for a certain character, not a string. You should refer to the official documentation
Code example:
$a = 'abcdef.txt'; $b = '.php'; echo strrchr($a, $b);The output of the above code is: .txt
In other words, if $b is a string, only the first character will be used, and other subsequent characters will be ignored
Note: PHP provides the strstr function, why not provide the strrstr function, although it is very simple to implement it yourself
2, null and empty, 0, comparison of three values
In PHP, == will first perform type conversion and then compare, while === will first compare types. If the types are different, unequal will be returned directly. Refer to the following example
$a = null; $b = ''; $c = 0; echo ($a == $b)?1:0; // 输出1 echo ($a === $b)?1:0; // 输出0 echo ($a == $c)?1:0; // 输出1 echo ($a === $c)?1:0; // 输出0 echo ($b == $c)?1:0; // 输出1 echo ($b === $c)?1:0; // 输出0For a coder like me who only wrote js or C# code before, I have been fooled by these three values n times, n is greater than 3
3. Reference assignment in foreach , please refer to the official documentation
This reference assignment is very good. For me who uses C#, it is impossible to modify the foreach element in C#, and an exception will occur. PHP makes this possible, but:
There is a warning in the official documentation: Warning The $value reference of the last element of the array will still be retained after the foreach loop. It is recommended to use unset() to destroy it.
Let’s look at a set of code:
$a = [1,2,3]; foreach($a as &$item){ echo $item . ','; } //unset($item); // 引用赋值后不销毁对象 foreach($a as $item){ echo $item . ','; }The output of the above code is as follows:
4. The connection and difference between isset and empty, isset document empty document
empty returns true in the following 8 situations:
null, empty string "", string 0 "0", empty array, Boolean value false, number 0, floating point number 0.0, defined with var in the class but not assigned
isset detects whether the variable is set and is not NULL, but for the 8 cases of empty, only null returns false, and the other 7 cases return true
In summary, except for the 7 non-null situations described by empty, in other cases, if(empty(variable)) is equivalent to if(!isset(variable))