Is there a short-circuit OR in PHP that returns the left-most value?

前端 未结 6 2051
南笙
南笙 2020-12-09 16:57

In some languages, you can do

$a = $b OR $c OR die(\"no value\");

That is, the OR will short-circuit, only evaluating values from left to right

6条回答
  •  挽巷
    挽巷 (楼主)
    2020-12-09 17:12

    You could use some kind of coalesce function:

    function coalesce() {
        foreach (func_get_args() as $arg) {
            if ($arg) {
                return $arg;
            }
        }
        return null;
    }
    
    $a = coalesce($a, $b) or die("no value");
    

提交回复
热议问题