"if" "and" 使用三元运算符的语句
"if" "and" statements using ternary operators
以下构建 link:
if ($cta) {
$cta = vc_build_link($cta);
$cta_href = strip_tags(trim($cta['url']));
$cta_text = strip_tags(trim($cta['title']));
}
目前后台如果$cta_href
或$cta_text
为空字段,会抛出undefined variable errors
.
我正在尝试使用三元运算符调整我的代码以使其更具可读性。
要解决 undefined variable
错误,我 想做 :
如果$add_cta
等于yes
(用户想在这个部分添加一个按钮)然后检查$cta_href
和$cta_text
是否为空。如果它们不是 empty
,则显示锚标记标记。
我目前有:
echo ($add_cta == "yes" ? '<a class="button " href="'.$cta_href.'">'.$cta_text.'</a>' : "");
但是,我找不到任何关于在三元语句中使用 and
的信息?
我该怎么做?我当前的伪代码是解决这个问题的最佳方法吗?
在 IF 语句中使用您的条件怎么样?
echo ($add_cta == "yes" && !empty($cta_href) && !empty($cta_text) ? '<a class="button " href="'.$cta_href.'">'.$cta_text.'</a>' : "");
三元运算符就是
/* condition */ ? /* true value */ : /* false value */ ;
因此您可以像在 IF、WHILE 等语句中那样自由编写条件。
但是三元运算符并不一定意味着你的代码会更好。
更简单的东西会更容易本能地阅读。
if($add_cta == "yes" && !empty($cta_href) && !empty($cta_text) ){
echo '<a class="button " href="'.$cta_href.'">'.$cta_text.'</a>';
}
以下构建 link:
if ($cta) {
$cta = vc_build_link($cta);
$cta_href = strip_tags(trim($cta['url']));
$cta_text = strip_tags(trim($cta['title']));
}
目前后台如果$cta_href
或$cta_text
为空字段,会抛出undefined variable errors
.
我正在尝试使用三元运算符调整我的代码以使其更具可读性。
要解决 undefined variable
错误,我 想做 :
如果$add_cta
等于yes
(用户想在这个部分添加一个按钮)然后检查$cta_href
和$cta_text
是否为空。如果它们不是 empty
,则显示锚标记标记。
我目前有:
echo ($add_cta == "yes" ? '<a class="button " href="'.$cta_href.'">'.$cta_text.'</a>' : "");
但是,我找不到任何关于在三元语句中使用 and
的信息?
我该怎么做?我当前的伪代码是解决这个问题的最佳方法吗?
在 IF 语句中使用您的条件怎么样?
echo ($add_cta == "yes" && !empty($cta_href) && !empty($cta_text) ? '<a class="button " href="'.$cta_href.'">'.$cta_text.'</a>' : "");
三元运算符就是
/* condition */ ? /* true value */ : /* false value */ ;
因此您可以像在 IF、WHILE 等语句中那样自由编写条件。
但是三元运算符并不一定意味着你的代码会更好。
更简单的东西会更容易本能地阅读。
if($add_cta == "yes" && !empty($cta_href) && !empty($cta_text) ){
echo '<a class="button " href="'.$cta_href.'">'.$cta_text.'</a>';
}