Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/php/296.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Php 设置var的简写方法=两个变量中较大的一个_Php_Syntax - Fatal编程技术网

Php 设置var的简写方法=两个变量中较大的一个

Php 设置var的简写方法=两个变量中较大的一个,php,syntax,Php,Syntax,我在等式中使用了两个不同的可能值。我想用最少的代码选择存在的和更大的。可能两个变量都不存在,在这种情况下year=0,但可能存在一个或两个变量。即: if(isset($this->average['year'] || isset($this->Listings['year']) { $year = whichever is greater of the above. } else { $year = 0; } 似乎必须有一种比以下方法更短/更少混乱的方法: if (isset($

我在等式中使用了两个不同的可能值。我想用最少的代码选择存在的和更大的。可能两个变量都不存在,在这种情况下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;
}
感谢使用和三元运算符对这两个变量执行
isset
检查,您可以将其缩短为:

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

看起来很整洁!谢谢-我会试试。如果不清楚,如果两者都没有设置,结果将是
0
max(数组(0,0))
正如John在他的答案中所说,编写一个像
$this->getMaxYear()
这样的方法来包含这个逻辑是明智的。谢谢!这非常有用:)