2013-04-09 19 views
0

改进is_array语句三元操作PHP的foreach

if (is_array($this->input->post("tolerance"))) 
    foreach($this->input->post("tolerance") as $tolerance) 
      $tolerances  .= $tolerance . " " ; 
else 
    $tolerances = 'Not defined'; 

我想简短的代码,因为我们都知道,我们正在核实,如果是前一种站前阵值的数组

等什么将是正确的方法来缩短这个?

is_array($this->input->post("tolerance")) ? foreach($this->input->post("tolerance") as tolerance) $tolerances .= $tolerance . " " : $tolerances = 'Not defined'; 
+0

使用较短的变量名称。严重:不要缩短它,你将永远无法再次阅读和理解你的代码 – kero 2013-04-09 15:56:06

+1

要小心:它具有可读代码比'缩短'的代码更好 - 这里没有什么可以获得的,我觉得... - 我会在代码块中加一些大括号 - 只是为了让它变得非常清晰...... – 2013-04-09 15:57:21

+0

**为什么**要缩短代码?它不是按原样工作吗?另外,我发现缺失的大括号是一种不好的习惯,如果你使用它们,代码更具可读性 – 2013-04-09 15:57:53

回答

1

我想不出什么好办法这样做,但要平均,做一个:

/* @ == ignore expected warning, $r == assign on testing */ 
$tolerances = ($r = @implode(' ', $this->input->post("tolerance"))) ? $r : 'Not defined'; 

我知道,大多数人认为这是不好的做法。

另一种选择,使用的foreach:

$tolerances = is_array($arr=$this->input->post("tolerance")) ? call_user_func(function($p) { foreach($p as $t) $ts .= $t . " "; return $ts;}, $arr) : 'Not defined'; 

只是继“坏习惯”的理念:如果可能的话,它的意思是。

3

你应该/不能同时保持foreach缩短这个在所有。三元运算符并不意味着要这样使用。它用于表达式,而不是用于语句。

很好的例子:

$foo = xyz() ? 'foo' : 'bar'; 

错误的例子:

xyz() ? foo() : bar(); 

更糟糕的例子(语法错误):

is_array($foo) ? foreach($foo as $bar) ... 

缩短你的代码中的唯一正确方法是使用一个临时变量和implode,而不是循环:

$tolerance = $this->input->post('tolerance'); 
$tolerance = is_array($tolerance) ? implode(' ', $tolerance) : 'Not defined'; 

在这种情况下,三元运算符是完全正常的,因为现在你只需要在随后/其他部分,而不是语句的表达。

+0

有没有办法缩短这个? – cMinor 2013-04-09 15:55:16

+0

看到我的编辑.... – ThiefMaster 2013-04-09 15:59:06

+0

以及你可以保持foreach种..看到我的文章(包装成call_user_func()调用) – BananaAcid 2013-04-10 10:37:06

2

尝试用implode(),像这样:

$tolerances = is_array($this->input->post("tolerance")) ? implode(' ', $this->input->post("tolerance")) : 'Not defined' ; 
0
$tolerances = (is_array($this->input->post("tolerance")) == false) ? "Not defined" : implode(" ", implode($this->input->post("tolerance"))) ; 
+0

无论如何,当你处理布尔时,'== false'和'== true'真的很糟糕 – ThiefMaster 2013-04-09 16:02:38