Home > Backend Development > PHP Tutorial > 20+ common PHP tips worth collecting (share)

20+ common PHP tips worth collecting (share)

青灯夜游
Release: 2023-04-10 12:48:01
forward
2530 people have browsed it

This article will share with you some commonly used techniques and methods in actual PHP development, so that everyone can spend more time fishing. Come and collect and learn!

20+ common PHP tips worth collecting (share)

1. Solve cross-domain problems

public function __construct()
{
    parent::__construct();
    header('Access-Control-Allow-Origin:*');    //跨域
}
Copy after login

2.json_encode Chinese No transcoding

die( json_encode( $result,JSON_UNESCAPED_UNICODE ) );
Copy after login

3. Two-dimensional array sorting

$users = array(
    array('name' => 'xiao1', 'age' => 20),
    array('name' => 'xiao2', 'age' => 18),
    array('name' => 'xiao3', 'age' => 22)
);
 
/*按照年龄升序*/
//要将age提取出来存储到一维数组里,然后按照age升序排列
$ages= array_column($users, 'age');
array_multisort($ages, SORT_ASC, $users);
 
/*先按照年龄升序,再按照姓名降序*/
$ages= array_column($users, 'age');
$names = array_column($users, 'name');
array_multisort($ages, SORT_ASC, $names, SORT_DESC, $users);
Copy after login

4. If php.ini on the Linux server closed the error prompt, resulting in results of 406, 500. Print error message.

ini_set("display_errors", "On");
error_reporting(E_ALL | E_STRICT);
Copy after login

5. The use of list

//list使用
public function test(){
    list($name, $sex) = $this->getInfo();
    echo "姓名:{$name},性别:{$sex}";
}
 
public function getInfo(){
    return ['张三', '男'];
}
 
//输出:姓名:张三,性别:男
Copy after login

6. The use of function array_column() Use

$array = [
    ['id'=>'99', 'name'=>'九十九'],
    ['id'=>'88', 'name'=>'八十八'],
    ['id'=>'77', 'name'=>'七十七'],
];
$arr1 = array_column($array, 'name');   
//输出:array (0 => '九十九',1 => '八十八',2 => '七十七',)
$arr2 = array_column($array, 'name', 'id'); 
//输出:array (  99 => '九十九',  88 => '八十八',  77 => '七十七',)
Copy after login
  • array_column() with array_combine()

$ids = array_column($array, 'id');
$arrayCombine = array_combine($ids, $array);
/*$arrayCombine 输出:
 array ( 
     99 => array ( 'id' => '99', 'name' => '九十九', ), 
     88 => array ( 'id' => '88', 'name' => '八十八', ), 
     77 => array ( 'id' => '77', 'name' => '七十七', ), 
 )*/
Copy after login

7, One-dimensional array deduplication, delete 0, null, index reset

$array = array(0,1,0,2,null,1,3,4,null,0);
$array = array_values(array_unique(array_diff($array, [0, null])));	//去除0,null;去重
var_export($array);
 
/*输出:
array (
  0 => 1,
  1 => 2,
  2 => 3,
  3 => 4,
)
*/
Copy after login

8. Convert seconds to hours, minutes and seconds

$r = gmstrftime('%H:%M:%S',(3600*23)+123);
var_export($r);
//输出: '23:02:03'
Copy after login

9. The interface returns

  • The interface returns 1 normally and -1 abnormally. If the data is empty, it is 1; -1 is a parameter exception or logic error.

10. Round to 2 decimal places.

round($x, 2);
Copy after login

11. Hide the middle 4 digits of your mobile phone number.

$num = "13711111111";
$str = substr_replace($num,'****',3,4);
Copy after login

12. Line break variable PHP_EOL

Usage scenario: A small line break actually works on different platforms There are different implementations.

Originally, /n is used to replace line breaks in the Unix world, but in order to reflect the difference, Windows uses /r/n. What is more interesting is that /r is used in Mac.

PHP_EOL is a variable that has been defined in php, representing the newline character of php.

This variable will change according to the platform. It will be /r/n under windows, /n under linux, and /r under mac.

13. PHP determines whether the array key exists isset(), array_key_exists(), empty()

$array = ['a'=>'我是第一个', 'b'=>'我是第二个', 'c'=>'我是第三个', 'f' => null];
if(isset($array['a'])) {
    echo 'a存在 ';
} else {
    echo 'a不存在 ';
}

if(array_key_exists('d', $array)) {
    echo 'd存在 ';
} else {
    echo 'd不存在 ';
}

if (empty($array['f'])) {
    echo 'f不存在';
} else {
    echo 'f存在,且不为 null,0,"0",false';
}
 
//a存在 d不存在 f不存在
Copy after login

14. Import js files with parameters?_=1553829159194

Sometimes there are such parameters after some addresses ?_=1553829159194

  • http://***/index/index?_=1553829159194
  • Add a timestamp timestamp after the url to ensure that the url changes every time so that it will not be read. The browser cached it.

15. Interface testing tool

  • Recommended interface testing tool postman

16. If the last word is "区", delete it.

$distName = '南山区';
$lastChar = mb_substr($distName, -1);
if($lastChar=='区'){
    $lastChar = mb_substr($distName, 0, -1);
}
echo $lastChar;
Copy after login

17. Assume that the page content is as follows:

  • The data structure returned by the background:
{"eat":["大米","小麦"],"drink":["水","茶"]}
Copy after login
  • It’s not good, so the front end needs to correspond to the relevant fields, eat is for eating; drink is for drinking.

  • It is best to return like this:

[{"name":"吃的","list":["大米","小麦"]},{"name":"喝的","list":["水","茶"]}]
Copy after login

18. Create the 0777 directory, use mkdir and chmod together

  • There is no problem in Windows when using mkdir to create a folder, but when using mkdir to create a folder in Linux, the maximum permissions will be 0777; so you need to use the chmod function again (the chmod function is created for Linux Insufficient folder permissions)
//若目录不存在则创建目录
$filePath = '../file/20900101';
if(@!file_exists($filePath)){
    mkdir($filePath, 0777, true);
    chmod($filePath, 0777);
}
Copy after login

19. Reference assignment in foreach

  • Code
$temp = [
            [ 'id' => 1, 'name' => 'name1', 'age' => 'age1', 'time' => 'time1' ],
            [ 'id' => 2, 'name' => 'name2', 'age' => 'age2', 'time' => 'time2' ]
        ];

# 清空原数据
$data = $temp;
foreach ($data as &$value){
    $value = [];
}
echo &#39;<pre class="brush:php;toolbar:false">&#39;;
print_r($data);

# 重置原数据
$data = $temp;
foreach ($data as &$value){
    $value = [
        &#39;hobby&#39; => 1
    ];
}
print_r($data);

# 追加原数据
$data = $temp;
foreach ($data as &$value){
    $value[&#39;hobby&#39;] = 1;
}
print_r($data);
Copy after login
  • Print
Array
(
    [0] => Array
        (
        )

    [1] => Array
        (
        )

)
Array
(
    [0] => Array
        (
            [hobby] => 1
        )

    [1] => Array
        (
            [hobby] => 1
        )

)
Array
(
    [0] => Array
        (
            [id] => 1
            [name] => name1
            [age] => age1
            [time] => time1
            [hobby] => 1
        )

    [1] => Array
        (
            [id] => 2
            [name] => name2
            [age] => age2
            [time] => time2
            [hobby] => 1
        )

)
Copy after login

20, url generator

public function test() {
	$url = self::getUrl(&#39;http://www.test.com&#39;, [&#39;id&#39; => 3, &#39;other&#39; => &#39;好的&#39;]);
	echo $url . &#39;<br>&#39;;     //打印:http://www.test.com?id=3&other=%E5%A5%BD%E7%9A%84
	echo urldecode($url);   //打印:http://www.test.com?id=3&other=好的
}

public function getUrl($apiUrl, $param = []){
    $param = http_build_query($param);
    return $apiUrl . &#39;?&#39; . $param;
}
Copy after login

21 , the write interface empty array returns the object form

  • $data is emptyAfter being forced to the object type, The value of json_encode is {}, if is not forced to be converted, it will be ==[]==, whether it is necessary to be forced to be converted depends on the actual situation
$data = $data ? $data : (object)$data;
Copy after login

Original address: https://juejin.cn/post/6973956902094897189 (updated from time to time)

Author: The motivated Dongbo Snow Eagle

Recommended learning: "PHP Video Tutorial"

The above is the detailed content of 20+ common PHP tips worth collecting (share). For more information, please follow other related articles on the PHP Chinese website!

Related labels:
php
source:掘金--有上进心的东伯雪鹰
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