Some PHP coding tips (php tips) [2011/04/02 Last updated]_php tips

Source: Internet
Author: User
Tags anonymous explode
Last Updated: 2011/04/02

1. Use the list to achieve a specific segment value after getting explode:
List (, $mid) = explode ('; ', $string);
2. Use NULL = = to replace Is_null:
Is_null and NULL = = are exactly the same effect, but save a function call.

3. Use = = = As far as possible without = =:
PHP has two sets of equality comparison operators ===/!== and ==/!=, ==/!= have implicit type conversions, and ===/!== will strictly compare two operations for the same type and equal values.
We should try to use = = = instead of = =, except because the conversion rules are more difficult to remember, there is a point is that if you use = =, for future maintenance or read your code will be very comfortable: "At this moment, this line of statements, this variable is this type!".

4. Less use/no continue:
Continue is back to the head of the loop, and the end of the loop is back to the head of the cycle, so by proper construction we can avoid using this statement and make the efficiency better.

5. Be wary of loose comparisons of Switch/in_array (loose comparision):
Both switch and In_array are loosely compared, so it's easy to make mistakes when the types of variables you want to compare are different:

Copy Code code as follows:

Switch ($name) {
Case "Laruence":
...
Break
Case "Eve":
...
Break
}

For the switch above, 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 want before switching to the switch.
Copy Code code as follows:

Switch (Strval ($name)) {
Case "Laruence":
...
Break
Case "Eve":
...
Break
}


Instead, In_array provides a third optional parameter, which allows you to change the default comparison method.
6. Switch is not only used to discriminate variables:
For example, for the following section of code:
Copy Code code as follows:

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

Can be simply rewritten as:
Copy Code code as follows:

Switch (TRUE) {
Case $a:
Break
Case $b:
Break
Case $C:
Case $d:
Break
}

Does it look clearer?
7. Variables are defined first and then used:
Using an undefined variable is 8 times times slower than using a well-defined variable!
As you can imagine, the PHP engine will first get the variable in the normal logic, but the variable does not exist, so the PHP engine needs to throw a notice and go into a section of logic that uses undefined variables and then returns a new variable.
Also, reading the code's point of view, when you use an undefined variable, it makes the person who reads your code confused: "Where is the variable initialized, related to the previous code?" Does it have anything to do with the file included? "
Finally, you need to do this in terms of normative programming.
8. Exchange the value of two variables without a third variable:
List ($a, $b) = Array ($b, $a),
But in fact, there are still anonymous temporary variables, for integers, using the inverse of the operation to do, or more reliable:
Copy Code code as follows:

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

However, it is still different or better, because +–*/easy to produce precision loss or overflow.
9. Floor = = two times non operation (this article is provided by Skiyo)
Copy Code code as follows:

Echo ~~4.9;
echo Floor (4.9);

The speed of the two-floor is basically 3 times times that of the same, but there is a point where the overflow may occur for a large number of times:
Copy Code code as follows:

Echo ~~99999999999999.99; 276447231
echo Floor (99999999999999.99); 99999999999999

Do{}while (0) Magical (this article is provided by Qianfeng)
We know that Do{}while (0) has many magical uses in C + +, such as eliminating Goto, and defining code blocks for macros.
So, PHP in the same, can also use Do{}while (0) to do some clever application
Copy Code code as follows:

do{
if (true) {
Break
}
if (true) {
Break
}
} while (false);
Better
if (true) {
else if (true) {
} else {
}

11. Use @ ERROR suppressor as little as possible
The following code:
Copy Code code as follows:

@func ();

is equivalent to (see deep understanding of the PHP principle of error suppression and embedded HTML):
Copy Code code as follows:

$report = error_reporting (0);
Func ();
Error_reporting ($report);

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

function f ($n) {
if ($n = 0) return 1;
Return $n * F ($n-1);
}
Into:
$result = 1;
for ($y = 1; $y < $n + 1; $y + +) {
$result *= $y;
}

13. Use $_server[' request_time '] instead of time ()
Time () will lead to a function call, and if the precise value of the timing is not high, you can use $_server[' request_time '] instead, a lot faster.
14. Avoid doing operations in the for-judge condition (this one comes from the anonymous of the message)
Like the following code:
for ($i =0; $i <strlen ($STR); $i + +) {
}
Causes each loop to invoke Strlen, instead
For ($i =0, $j =strlen ($STR); $i < $j; $i + +) {
}
15. Avoid the use of regular (this article from Pangyontao)
Regular time consuming, as far as possible, rather than using a direct string-handling function instead, such as:
Copy Code code as follows:

if (Preg_match ("!^foo_!i", "Foo_")) {}
To be replaced by:
if (!strncasecmp ("Foo_", "Foo_", 4)) {}
if (Preg_match ("![ A8f9]! "," Sometext ")) {}
To be replaced by:
if (STRPBRK ("A8f9", "Sometext")) {}
if (Preg_match ("!string!i", "text")) {}
To be replaced by:
if (Stripos ("Text", "string")!== false) {}

Wait a minute.
16. Variables enclosed in double quotes and heredoc with curly braces
Like the following code:
echo "$name [2]";
PHP does not know that the programmer's intent is $name. "[2]" or $name[2],
So it's recommended to add braces:
Copy Code code as follows:

echo "{$name}[2]";
Or
echo "${name}[2]";

17. Use False to indicate an error and NULL to indicate that it does not exist.
For a function of the action class, the failure returns false, which means "the operation failed," and for the function of the query class, if the desired value is not found, it should return null, indicating "not found".

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.