设置var的缩写,以2个变量中较大者为准

时间:2014-05-22 00:22:04

标签: php syntax

我在方程中使用了2个不同的可能值。我想选择存在的任何一个,并使用最少的代码更大。可能两个变量都不存在,在这种情况下,year = 0,但可能存在一个或两个。即:

if(isset($this->average['year'] || isset($this->Listings['year']) {
$year = whichever is greater of the above.
} else {
$year = 0;
}

似乎必须有一个更短/更少杂乱的方式来做到这一点:

if (isset($this->average['year']) && ($this->average['year'] > $this->Listings['year']) {
   $year = $this->average['year'];
} elseif( isset($this->Listings['year'])) {
   $year = $this->Listings['year'];
} else {
  $year = 0;
}

由于

1 个答案:

答案 0 :(得分:1)

使用max和三元运算符对两个变量进行isset检查,您可以将其缩短为:

$year = max(array(
    isset($this->average['year']) ? $this->average['year'] : 0,
    isset($this->Listings['year']) ? $this->Listings['year'] : 0
));