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

20+ common PHP tips worth collecting (share)

青灯夜游
青灯夜游forward
2021-07-29 18:47:172503browse

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:*');    //跨域
}

2.json_encode Chinese No transcoding

die( json_encode( $result,JSON_UNESCAPED_UNICODE ) );

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);

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);

5. The use of list

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

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 => '七十七',)
  • 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' => '七十七', ), 
 )*/

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,
)
*/

8. Convert seconds to hours, minutes and seconds

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

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);

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

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

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不存在

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;

17. Assume that the page content is as follows:

  • The data structure returned by the background:
{"eat":["大米","小麦"],"drink":["水","茶"]}
  • 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":["水","茶"]}]

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);
}

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 'e03b848252eb9375d56be284e690e873';
print_r($data);

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

# 追加原数据
$data = $temp;
foreach ($data as &$value){
    $value['hobby'] = 1;
}
print_r($data);
  • 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
        )

)

20, url generator

public function test() {
	$url = self::getUrl('http://www.test.com', ['id' => 3, 'other' => '好的']);
	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;
}

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;

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!

Statement:
This article is reproduced at:掘金--有上进心的东伯雪鹰. If there is any infringement, please contact admin@php.cn delete