Home  >  Article  >  Backend Development  >  Some PHP Coding Tips (php tips) [Last updated on 2011/04/02]_PHP Tutorial

Some PHP Coding Tips (php tips) [Last updated on 2011/04/02]_PHP Tutorial

WBOY
WBOYOriginal
2016-07-21 15:30:34783browse

Last updated: 2011/04/02

1. Use list to obtain the specific segment value after explode at one time:
list( , $mid) = explode(';', $string);
2. Use NULL === instead of is_null:
is_null and NULL === have exactly the same effect, but save a function call.

3. Try not to use === ==:
PHP has two sets of equality comparison operators ===/!== and ==/!=, ==/!= will have implicit type conversion, while ===/!== will be strict When comparing two operations, whether they are of the same type and have equal values.
We should try to use === instead of ==. In addition to the fact that the conversion rules are difficult to remember, another point is that if === is used, it will not be easy to maintain in the future. Or people who read your code will also feel comfortable: "At this moment, this line of statement, this variable is of this type!".

4. Use less/no continue:
continue is to return to The head of the loop, and the end of the loop is to return to the head of the loop, so through appropriate construction, we can completely avoid using this statement, which improves efficiency.

5. Be wary of switch/in_array, etc. Loose comparison:
switch and in_array both use loose comparison, so when the types of variables to be compared are different, it is easy to make mistakes:

Copy code The code is as follows:

switch ($name) {
case "laruence":
...
break;
case "eve":
...
break;
}

For the above switch, if $name is the number 0, then it will satisfy any case. The same is true in in_array.
The solution is to convert the variable type to the type you expect before switching.
Copy code The code is as follows:

switch (strval($name)) {
case "laruence":
...
break;
case "eve":
...
break;
}


However, in_array provides a third optional parameter, through which the default comparison method can be changed.
6. Switch is not only used to identify variables:
For example, for the following piece of code:
Copy the code The code is as follows:

if($a) {
} else if ($b) {
} else if ($c || $d) {
}

It can be simply rewritten as:
Copy the code The code is as follows:

switch (TRUE) {
case $a:
break;
case $b:
break;
case $c:
case $d:
break;
}

Yes Doesn’t it look clearer?
7. Define variables first and then use them:
Using an undefined variable is more than 8 times slower than using a defined variable!
It can be similar, the PHP engine will First, follow the normal logic to get this variable, but this variable does not exist, so the PHP engine needs to throw a NOTICE, and enter a section of logic that should be followed when using undefined variables, and then return a new variable.
In addition, From the perspective of reading code, when you use an undefined variable, it will confuse people who read your code: "Where is this variable initialized? Does it have anything to do with the previous code? Does it have anything to do with the included file?" ”
Finally, from a standard programming perspective, you also need to do this.
8. Exchange the values ​​of two variables without a third variable:
list($a, $b) = array( $b, $a),
But in fact there are still anonymous temporary variables. For integers, it is more reliable to use reciprocal operations:
Copy the code The code is as follows:

$a = $a + $b;
$b = $a - $b;
$a = $a - $b;

However, it is better to use XOR, because + – * / is prone to precision loss or overflow.
9. floor == two NOT operations (this article is provided by skiyo Provided)
Copy code The code is as follows:

echo ~~4.9;
echo floor(4.9);

The speed of using two NOT operations is basically 3 times that of floor, but there is one thing, for large numbers, overflow may occur:
Copy Code The code is as follows:

echo ~~9999999999999.99; //276447231
echo floor(99999999999999.99); //99999999999999

10. The wonderful uses of do{}while(0) (this article is provided by Qianfeng)
We know that do{}while(0) has many wonderful uses in c/c++, such as eliminating goto and macro definition code blocks.
So , the same is true in PHP, you can also use do{}while(0) to do some clever applications
Copy code The code is as follows:

do{
if(true) {
break;
}
if(true) {
break;
}
} while(false) ;
//Better than
if(true) {
} else if(true) {
} else {
}

11. Use @ as little as possible The error suppressor
has the following code:
Copy the code and the code is as follows:

@func();

is equivalent to (see in-depth understanding of PHP principles: error suppression and embedded HTML):
Copy code The code is as follows:

$report = error_reporting(0);
func();
error_reporting($report);

In addition, error suppression symbols may cause some problems, see (http://www.jb51.net/article/27022.htm);
Finally, error suppressors may also cause trouble when error debugging occurs.
12. Try to avoid using recursion (this Article from lazyboy)
Recursion performance is worrying, and most of the recursion is tail recursion, which can be eliminated.
Copy code The code is as follows:

function f($n) {
if ($n = 0) return 1;
return $n * f($n - 1);
}
//Changes to:
$result = 1;
for ($y = 1; $y < $n + 1; $y++ ) {
$result *= $y;
}

13. Use $_SERVER['REQUEST_TIME'] instead of time()
time() will cause a function call, but if the precise value of time is not high, you can use $_SERVER['REQUEST_TIME'] instead, which is much faster.
14. Avoid doing operations in the for judgment condition (this article comes from Anonymous in the message)
The following code:
for($i=0; $i}
will cause strlen to be called every time in the loop, change it to
for ($i=0, $j=strlen($str); $i<$j; $i++) {
}
15. Try to avoid using regular expressions (this article comes from pangyontao)
Regular expressions are time-consuming, try to avoid them, and use direct string processing functions instead, such as :
Copy code The code is as follows:

if (preg_match("!^foo_!i", "FoO_")) { }
// Replaced with:
if (!strncasecmp("foo_", "FoO_", 4)) { }
if (preg_match("![a8f9]!", "sometext") ) { }
// Replace with:
if (strpbrk("a8f9", "sometext")) { }
if (preg_match("!string!i", "text")) {}
// Replace with:
if (stripos("text", "string") !== false) {}

etc.
16. Use braces Variables enclosed in double quotes and heredoc
The following code:
echo "$name[2]";
PHP does not know whether the programmer intended $name. "[2]" or $ name[2],
Therefore, it is recommended to add curly brackets:
Copy code The code is as follows:

echo "{$name}[2]";
//or
echo "${name}[2]";

17. Use FALSE to indicate errors and NULL to indicate no Exists.
For operation class functions, failure returns FALSE, which means "the operation failed", while for query class functions, if the desired value cannot be found, it should return NULL, which means "cannot be found".

www.bkjia.comtruehttp: //www.bkjia.com/PHPjc/323227.htmlTechArticleLast updated: 2011/04/02 1. Use list to obtain the specific segment value after explode at one time: list ( , $mid) = explode(';', $string); 2. Use NULL === instead of is_null: is_null and NULL === End...
Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn