简体   繁体   中英

“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 .

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 :

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. If they're not empty , then show the anchor tag markup.

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?

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 ?

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.

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>';
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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