Some PHP Coding Tips「待更新」

WBOY
Release: 2016-06-23 13:34:14
Original
1047 people have browsed it

1、使用list来实现一次获取explode后的特定段值:

<?phplist( , $mid) = explode(';', 'aa;bb;cc');echo $mid; //输出 bb
Copy after login

2、注意 == 、switch、in_array 的松比较 (loose comparision)

例如下边的例子中,如果 $name 值为 0,那么它会满足任何一条 case。

switch ($name) {    case "danny":        ...        break;    case "eve":        ...        break;}
Copy after login

解决方法:在 switch 之前,把变量类型转换成所期望的类型。 而 in_array 提供了第三个参数,如果第三个参数的值为 TRUE 则 in_array() 函数还会检查变量的类型是否相同。(参考:https://php.net/manual/zh/function.in-array.php)

switch (strval($name)) {    case "danny":        ...        break;    case "eve":        ...        break;}
Copy after login

3、用 switch 来改写 if else

例如:

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

可以简单改写为更清晰的:

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

4、不用第三变量交换俩个变量的值

list($a, $b) = array($b, $a);

5、使用 array_map 遍历数组

在从数据库取回记录后,经常要 foreach 去取其中一个字段,这时就可以使用 array_map 来简化代码。

$uids = array_map( function($user){ return $user['id']; } , $users );
Copy after login

参考:
1、http://www.laruence.com/2011/03/24/858.html
2、http://get.jobdeer.com/75.card

source:php.cn
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
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!