php if 判断的问题。
Jun 06, 2016 pm 08:11 PM
有一段php的判断大家看看有没有更简洁的写法,或者别的方式可以实现
<code>$cat_id = 0; if(empty($a)){ if(empty($b)){ if(empty($c)){ return 0; exit(); }else{ $cat_id = $c; } }else{ $cat_id = $b; } }else{ $cat_id = $a; } </code>
回复内容:
有一段php的判断大家看看有没有更简洁的写法,或者别的方式可以实现
<code>$cat_id = 0; if(empty($a)){ if(empty($b)){ if(empty($c)){ return 0; exit(); }else{ $cat_id = $c; } }else{ $cat_id = $b; } }else{ $cat_id = $a; } </code>
<code>$cat_id = $a ?: $b ?: $c ?: 0; //对PHP版本有要求</code>
喜欢这么写,没有嵌套
<code>$cat_id = 0; if($a) { $cat_id = $a; return; } if($b) { $cat_id = $b; return; } if($c) { $cat_id = $c; return; } return;</code>
$cat_id = $a ? $a : ($b ? $b : ($c ? $c : 0));
$cat_id = 0; if (!empty($a)) { $cat_id = $a; } elseif (!empty($b)) { $cat_id = $b; } elseif (!empty($c)) { $cat_id = $c; } else { return 0; }
<code>function test($a, $b, $c) { if (empty($a)) { if (empty($b)) { if (empty($c)) { return 0; } return $c; } return $b; } return $a; } $cat_id = test($a, $b, $c);</code>
应该是没有更简单的写法了,但是可以优化成
<code>$cat_id = 0; if (! empty($c)) $cat_id = $c; if (! empty($b)) $cat_id = $b; if (! empty($a)) $cat_id = $a; if (empty($cat_id)) exit;</code>
<code> function checkEmpty($a, $b = '', $c = ''){ if(empty($b) && empty($c)) exit(); return empty($a) ? checkEmpty($b,$c) : $a; }</code>
这个应该够简洁了!
<code>$cat_id = 0; while(1){ if(empty($a)){ $cat_id = $a; break; } if(empty($b)){ $cat_id = $b; break; } if(empty($c)){ $cat_id = $c; break; } }</code>
不写嵌套就行了
可读性强
以简驭繁

Heißer Artikel

Hot-Tools-Tags

Heißer Artikel

Heiße Artikel -Tags

Notepad++7.3.1
Einfach zu bedienender und kostenloser Code-Editor

SublimeText3 chinesische Version
Chinesische Version, sehr einfach zu bedienen

Senden Sie Studio 13.0.1
Leistungsstarke integrierte PHP-Entwicklungsumgebung

Dreamweaver CS6
Visuelle Webentwicklungstools

SublimeText3 Mac-Version
Codebearbeitungssoftware auf Gottesniveau (SublimeText3)

Heiße Themen

PHP 8.4 Installations- und Upgrade-Anleitung für Ubuntu und Debian

So richten Sie Visual Studio-Code (VS-Code) für die PHP-Entwicklung ein
