Home > Backend Development > PHP Tutorial > Some practical tips for PHP

Some practical tips for PHP

Release: 2023-04-08 13:04:02
forward
2419 people have browsed it

Some practical tips for PHP

1. Convert string type number to number type

$str = '123';
//方法一
(int)$str;
//方法二
intval($str);
//方法三
+$str;
Copy after login

Methods 1 and 2 are forced conversions, even if the string contains letters after numbers. Method three must ensure that it is a pure numeric string, otherwise an error will be reported.

Recommended: "php training"

2. Add elements to the array

$arr = ['a'];
//方法一
array_push($arr,'b', 'c');
//方法二
$arr[] = 'd';
Copy after login

1. If you are pushing an element, how to use it 2. High efficiency because it can save the extra burden of calling functions.

2. If multiple elements are pushed at the same time, using array_push is efficient because there is no need to repeatedly obtain the pointer to the end of the file.

3. for loop

//正常写法
for($i = 0; $i < count($arr); $i++){
	//
}
//优化一
for($i = 0, $len = count($arr); $i < $len; $i++){
	//
}
//优化二
for($i = count($arr) - 1; $i > -1; --$i){
	//
}
Copy after login

Optimization 1: The problem is that the conditional judgment needs to calculate the length of the array every time. It is better to declare a variable to store it at the beginning. The for loop in other languages ​​is probably the same...

Optimization 2: When there is no need to increase from small to large, you can save a $len variable. There is also a small optimization - $i is faster than $i--.

Summary: It doesn’t mean that Optimization 2 is necessarily good, I just thought of this and wrote it. However, I think a good for loop should at least pay attention to optimization. In addition, $i can be changed to $i!

4. foreach traversal

//写法一
foreach($arr as $k => $v){
	//
}
//写法二
foreach($arr as $v){
	//
}
//写法三
foreach($arr as &$v){
	//	
}
//写法四
$arr = [
	[1,2,3],
	[4,5,6]
];
foreach($arr as list($a,$b,$c)){
	//
}
Copy after login

1. First of all, you need to know one thing. In the first and second writing methods, $v does not take the address. $v is A copy of the key value. So don't change the array/object itself in foreach, it's useless.

2. When there is no need for key names or indexes, don’t write $k. There is nothing to say about this.

3. Regarding writing method 3, address reference assignment, the advantage is that it saves space when the value is very large. But it should be noted that no matter which way you write it, $v will be retained after the foreach loop. If you use the address-taking method at this time, it will be bad to use $v again. The manual recommends unset($v).

4. The fourth writing method is for the application of two-dimensional arrays/objects, using list to unpack the key-value array. Note that if the number of variables received in the list is more than the length of the actual two-dimensional array, an error will be reported. If it is less, it will just not be received, so you still need to consider it when using it.

5. Regarding null judgment

//写法一
is_null($a);
//写法二
$a === null
Copy after login

The two writing methods have exactly the same effect. Use method two to save function calls.
Don’t use == if you can use ===.

6. Multiple judgments

$a = 1;
//写法一
if($a === 0){
	//
}elseif($a === 1){
	//
}else{
	//
}
//写法二
do{
	if($a === 0){
		//
		break;
	}
	if($a === 1){
		//
		break;
	}
	//
}while(false);
//写法三
switch(true){
	case 0:
		//
		break;
	case 1:
		//
		break;
	default:
		//
}
Copy after login

7. Magical use of list

//妙用一
list($a,$b) = [$b,$a];
//妙用二
list(,$fn) = explode(&#39;_&#39;,&#39;Api_deleteUser&#39;);
Copy after login

8. English string length exceeds limit

//一般方式
strlen($str) > 10;
//优化方式
isset($str[10]);
Copy after login

isset is a PHP statement, strlen is a function.

9. Several ways to write null judgment assignment

//当$a不为null时$b = $a,否则$b = 233333。
//方式一
$b = $a or $b = 233333;
//方式二
$b = $a ? $a : 23333;
//方式三
$b = $a ?: 233333;
//方式四,PHP7
$b = $a ?? 233333;
Copy after login

Pay attention to the difference between method three and method four, and make it clear what you want to judge. In addition to method four, the other three can also determine false,'','0',0,[].

10. Exchange two variables

//方式一:比较清晰,有变量产生
$temp = $a;
$a = $b;
$b = $temp;
//方法二:比较清晰,但也会产生临时变量
list($b, $a) = [$a,$b];
//方式三:在整数运算时互逆运算比较靠谱,但+ – * /可能精度丢失或溢出
$a = $a + $b;
$b = $a - $b;
$a = $a - $b;
Copy after login

11. Avoid using recursion

//递归
function fibonacci($n){
	if($n == 0 || $n == 1){
		return 1;
	}
	return fibonacci($n - 1) + fibonacci($n - 2);
}
//非递归
function fibonacci($n){
	$arr = [1,1];
	for($i = 2; $i < $n + 1; ++$i){
		$arr[] = $arr[$i - 1] + $arr[$i - 2];
	}
	return $arr[$n];
}
Copy after login

12. Do not omit the braces after if

//写法一
if($a === null) $a = 1;
//写法二
if($a === null)
	$a = 1;
//写法三
if($a === null){
	$a = 1;
}
//如果可以避免写if更好
$a = $a ?? 1;
Copy after login

13. Use $_SERVER['REQUEST_TIME'] replaces time().

The latter will cause a function call, and if the precise value of time is not required, the former is much faster.

14. Use less/no use 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, making the efficiency better Improvement.

15. Define variables first and then use them

Using an undefined variable is more than 8 times slower than using a defined variable!

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, enter a section of logic that should be followed when using undefined variables, and then return a new variable.

16. Regarding naming

According to the PSR specification, methods must use small camel case.

According to the PSR specification, class naming must be in camel case.

The naming of variables is not clear in the specification and should be unified within the project. (The underlined version is easier to understand)

Boolean variables should start with can, is, and has as much as possible.

17. Avoid using regular expressions

18. Use curly braces to enclose variables in double quotes and heredoc

For more programming related content, please pay attention to php Chinese websiteProgramming Tutorial column!

Related recommendations:

PHP video tutorial, learning address: https://www.php.cn/course/list/29/type/2.html

The above is the detailed content of Some practical tips for PHP. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
php
source:csdn.net
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template