Heim  >  Artikel  >  Backend-Entwicklung  >  php if 判断的问题。

php if 判断的问题。

WBOY
WBOYOriginal
2016-06-06 20:11:581469Durchsuche

有一段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));

<code class="php">$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>

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

不写嵌套就行了

可读性强

以简驭繁

Stellungnahme:
Der Inhalt dieses Artikels wird freiwillig von Internetnutzern beigesteuert und das Urheberrecht liegt beim ursprünglichen Autor. Diese Website übernimmt keine entsprechende rechtliche Verantwortung. Wenn Sie Inhalte finden, bei denen der Verdacht eines Plagiats oder einer Rechtsverletzung besteht, wenden Sie sich bitte an admin@php.cn