Search code examples
phpconcatenation

Streamlining PHP Concatenation with Conditional Statements


I'm trying to concatenate a string in PHP which is a verified tick badge, but I need to include a conditional statement inside the concatenation. Here's the code I have so far:

<?php if($data->verified): ?>
  <i class="fa fa-check-circle"></i>
<?php endif;?>

fetching comments data:

while($data = $result->fetch_object()) {
    $content .= '

    <div class="caption animated fadeIn">
            <a href="profile/' . $data->username . '"><img src="' . self::display_image(AVATARS_THUMBS_ROUTE . $data->avatar) . '" class="img-circle dashboard-avatar" alt="Avatar"/></a> <a href="profile/' . $data->username . '">' . $data->name . '</a><span>' . Messages::generate_emoticons(User::generate_links($data->content)) . '</span>
    </div>
    ';
}

Solution

  • Simply put the HTML in a variable, make it empty when you need, and concatenate it like you do with the rest:

    while($data = $result->fetch_object()) {
        if($data->verified) {
            $icon = '<i class="fa fa-check-circle"></i>';
        } else {
            $icon = '';
        }
        $content .= '
    
        <div class="caption animated fadeIn">
                <a href="profile/' . $data->username . '">'.$icon.'<img src="' . self::display_image(AVATARS_THUMBS_ROUTE . $data->avatar) . '" class="img-circle dashboard-avatar" alt="Avatar"/></a> <a href="profile/' . $data->username . '">' . $data->name . '</a><span>' . Messages::generate_emoticons(User::generate_links($data->content)) . '</span>
        </div>
        ';
    }