brianrhea
brianrhea

Reputation: 3724

Adding an IF statement to not print a link if its URL is an empty string

I have the following code from the developer of my Wordpress site and if possible I'd like to make a revision myself.

$list .= '<div class="fc_right">
    <h3>'.$headline.'</h3>
    <div class="fc_caption">'.$caption.'</div>
    <a href="'.$url.'">More &#187;</a>
  </div><div class="clear"></div>
</li>';

I just want to add an if statement in there that if $url is blank, then don't print the More>> link.

Let me know if I need to provide more context of the code, I wanted to keep it brief for you all if possible.

Upvotes: 2

Views: 103

Answers (5)

KingCrunch
KingCrunch

Reputation: 131891

$list .= '<div class="fc_right">
    <h3>'.$headline.'</h3>
    <div class="fc_caption">'.$caption.'</div>' .
    ($url ? '<a href="'.$url.'">More &#187;</a>' : '')
   . '</div><div class="clear"></div>
</li>';

Upvotes: 1

SeanCannon
SeanCannon

Reputation: 77976

$list .= '<div class="fc_right">
    <h3>'.$headline.'</h3>
    <div class="fc_caption">'.$caption.'</div>';

$list.= if(!empty($url)) ? ' <a href="'.$url.'">More &#187;</a>' : '';

$list.= '</div><div class="clear"></div>
</li>';

Upvotes: 0

user142162
user142162

Reputation:

$list .= '<div class="fc_right">
    <h3>'.$headline.'</h3>
    <div class="fc_caption">'.$caption.'</div>' .
    ($url == '' ? '' : '<a href="'.$url.'">More &#187;</a>') .
  '</div><div class="clear"></div>
</li>';

Upvotes: 3

Andrew Moore
Andrew Moore

Reputation: 95344

There is nothing stopping you from adding that if statement yourself...

$list .= '<div class="fc_right">
    <h3>'.$headline.'</h3>
    <div class="fc_caption">'.$caption.'</div>';

if($url) $list .= '<a href="'.$url.'">More &#187;</a>';

$list .= '</div><div class="clear"></div>
</li>';

Upvotes: 4

Jared Farrish
Jared Farrish

Reputation: 49208

Well, you could either do a string interpolation, or use a ternary:

$list .= '<div class="fc_right">
    <h3>'.$headline.'</h3>
    <div class="fc_caption">'.$caption.'</div>
    '.($url != ''?'<a href="'.$url.'">More &#187;</a>':'').'
  </div><div class="clear"></div>
</li>';

http://codepad.org/Vt6QbLwY

And in longform:

<?php

$url = '';

if ($url == '') {
    $s_url = '';
} else {
    $s_url = '<a href="'.$url.'">More &#187;</a>';
}

$list .= '<div class="fc_right">
    <h3>'.$headline.'</h3>
    <div class="fc_caption">'.$caption.'</div>
    '.$s_url.'
  </div><div class="clear"></div>
</li>';

echo $list;

?>

http://codepad.org/a9UisF9i

Upvotes: 0

Related Questions