php if 判断的问题。

WBOY
Release: 2016-06-06 20:11:58
Original
1516 people have browsed it

有一段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>
Copy after login
Copy after login

回复内容:

有一段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>
Copy after login
Copy after login

<code>$cat_id = $a ?: $b ?: $c ?: 0;
//对PHP版本有要求</code>
Copy after login

喜欢这么写,没有嵌套

<code>$cat_id = 0;

if($a) {
    $cat_id = $a;
    return;
}

if($b) {
    $cat_id = $b;
    return;
}

if($c) {
    $cat_id = $c;
    return;
}

return;</code>
Copy after login

$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>
Copy after login

<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>
Copy after login

应该是没有更简单的写法了,但是可以优化成

<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>
Copy after login

<code>    function checkEmpty($a, $b = '', $c = ''){
        if(empty($b) && empty($c)) exit();
        return empty($a) ? checkEmpty($b,$c) : $a;
    }</code>
Copy after login

这个应该够简洁了!

<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>
Copy after login

不写嵌套就行了

可读性强

以简驭繁

Related labels:
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