首页 > 解决方案 > 如何使我的 if 条件更简单?

问题描述

我试图找到一种更短的方法来编写这个 if 条件:

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

这是我的方法:

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

我觉得这段代码可以减少更多。但是我不知道怎么做。

标签: phpif-statement

解决方案


else 条件的代码似乎没用,因为您再次使用相同的值设置相同的变量。您只能使用 if 条件:

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

希望它可以帮助你。


推荐阅读