如果条件变得更简单,我该如何做?

时间:2019-02-13 17:11:13

标签: php if-statement

我正在尝试找到一种简短的if条件写方法:

if($template == "documents"){
  $slug = $template;
  $parent = "products";
} else {
  $slug = $slug;
  $parent = $parent;
}

这是我的方法:

$slug = ($template == "documents") ? $template : $slug;
$parent = ($template == "documents") ? "products" : $parent;

我觉得这段代码可以减少更多。但是我不知道如何。

4 个答案:

答案 0 :(得分:5)

其他条件的代码似乎无用,因为您再次用相同的值设置了相同的变量。您只能在以下情况下使用:

if ($template == "documents") {
    $slug = $template;
    $parent = "products";
}

希望它对您有帮助。

答案 1 :(得分:3)

您的第二个答案很小。您的第一个答案更长,但更易于维护。某些语言(Python和其他语言)支持多重分配,但不支持PHP或Perl。使用这些语言,您可以执行以下操作:

(slug, parent) = (template == "documents") ?
  (template,  "products") : (slug, parent)

答案 2 :(得分:1)

它的评估时间可能太短,例如:

($template == "documents")?($slug = $template AND $parent = "products"): ($slug = $slug AND $parent = $parent) 

注意:怀疑您正在使用php

答案 3 :(得分:1)

JoshGagliardi对答案的修改:

list($slug,$parent) = template == "documents" 
      ? array($template,"products") : array($slug,$parent);

无论如何,这对我来说是最好的(阅读):

if ($template == "documents") {
    $slug   = $template;
    $parent = "products";
}
相关问题