php if 判斷的問題。

來源:互聯網
上載者:User
有一段php的判斷大家看看有沒有更簡潔的寫法,或者別的方式可以實現

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

回複內容:

有一段php的判斷大家看看有沒有更簡潔的寫法,或者別的方式可以實現

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

$cat_id = $a ?: $b ?: $c ?: 0;//對PHP版本有要求

喜歡這麼寫,沒有嵌套

$cat_id = 0;if($a) {    $cat_id = $a;    return;}if($b) {    $cat_id = $b;    return;}if($c) {    $cat_id = $c;    return;}return;

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

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

應該是沒有更簡單的寫法了,但是可以最佳化成

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

    function checkEmpty($a, $b = '', $c = ''){        if(empty($b) && empty($c)) exit();        return empty($a) ? checkEmpty($b,$c) : $a;    }

這個應該夠簡潔了!

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

不寫嵌套就行了

可讀性強

以簡馭繁

  • 聯繫我們

    該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

    如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

    A Free Trial That Lets You Build Big!

    Start building with 50+ products and up to 12 months usage for Elastic Compute Service

    • Sales Support

      1 on 1 presale consultation

    • After-Sales Support

      24/7 Technical Support 6 Free Tickets per Quarter Faster Response

    • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.