Reputation: 867
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?
Upvotes: 0
Views: 149
Reputation: 5713
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>';
}
Upvotes: 1