简体   繁体   English

使用三元运算符的“ if”和“ if”语句

[英]“if” “and” statements using ternary operators

The following builds the link: 以下构建链接:

if ($cta) {
    $cta = vc_build_link($cta);
    $cta_href = strip_tags(trim($cta['url']));
    $cta_text = strip_tags(trim($cta['title']));
}

Currently, if $cta_href or $cta_text are empty fields in the backend, it will throw out undefined variable errors . 当前,如果$cta_href$cta_text在后端为空字段,它将抛出未定义的variable errors

I'm trying to adapt my code with the use of ternary operators to make it more readable. 我正在尝试使用三元运算符来修改我的代码,以使其更具可读性。

To resolve the undefined variable errors I'm looking to do : 为了解决undefined variable错误,我正在寻找

if $add_cta equals yes (the user wants to add a button to this section) then check if $cta_href and $cta_text are empty. 如果$add_cta等于yes (用户想在此部分添加按钮),则检查$cta_href$cta_text是否为空。 If they're not empty , then show the anchor tag markup. 如果它们不为empty ,则显示锚标记标记。

I currently have: 我目前有:

echo ($add_cta == "yes" ? '<a class="button " href="'.$cta_href.'">'.$cta_text.'</a>' : "");

But, I cannot find anything on the use of and within a ternary statement? 但是,在三元语句的使用and内部,我找不到任何东西吗?

How do I go about this? 我该怎么办? and is my current pseudo code the best way to approach this? 我当前的伪代码是解决此问题的最佳方法吗?

What about just having your condition as you would in a IF statement ? 就像在IF语句中那样让您的病情怎么样?

echo ($add_cta == "yes" && !empty($cta_href) && !empty($cta_text) ? '<a class="button " href="'.$cta_href.'">'.$cta_text.'</a>' : "");

A ternary operator is just 三元运算符就是

/* condition */ ? /* true value */ : /* false value */ ;

So you are free to write a condition as you would in a IF,WHILE, etc.. statement. 因此,您可以像在IF,WHILE等语句中那样自由编写条件。

But ternary operator doesn't necessarily mean your code will be better. 但是三元运算符并不一定意味着您的代码会更好。

Something simpler would be easier to read instinctively. 更简单的东西本能地更容易阅读。

if($add_cta == "yes" && !empty($cta_href) && !empty($cta_text) ){
    echo '<a class="button " href="'.$cta_href.'">'.$cta_text.'</a>';
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM