user13245598
user13245598

Reputation: 45

how to concatenate my strings with php in html

I know how to concatenate php variable but how about php if else script inside html? I have used below code:

    $output .='
    <div class="col-md-3 mb-4">
        <div class="card h-100">
          <img class="card-img-top"  src="../admin/upload/'. $row['images'].'" width="50px" height="300px" alt="Image">
          <div class="overlay">
            <p><strong> Title : </strong>'. $row['title'].'</p>
            <p><strong> Author : </strong>'. $row['author'].'</p>
            <p><strong> ISBN : </strong>'. $row['isbn'].'</p>

          </div>
          <div class="card-body">


            '.$status='';
            if ($row ['status'] == 'Available')
            {
              $status='success';
            }
            else if ($row ['status'] == 'Unavailable')
            {
              $status ='danger';
            }.'

<a href="book_details.php?title='. $row['title'].'&isbn='. $row['isbn'].'"> <button type="button"class="btn btn-'.$status.'">'. $row['status'].'</button></a>


          </div>
        </div>

      </div>';

How do I concatenate my strings especially when the php if else statement? Thanks for help

Upvotes: 1

Views: 594

Answers (2)

Eric
Eric

Reputation: 97591

You can use an anonymous function, and execute it immediately:

    $output .='
    <div class="col-md-3 mb-4">
        <div class="card h-100">
          <img class="card-img-top"  src="../admin/upload/'. $row['images'].'" width="50px" height="300px" alt="Image">
          <div class="overlay">
            <p><strong> Title : </strong>'. $row['title'].'</p>
            <p><strong> Author : </strong>'. $row['author'].'</p>
            <p><strong> ISBN : </strong>'. $row['isbn'].'</p>

          </div>
          <div class="card-body">


            '.call_user_function(function() use($row) {
            if ($row ['status'] == 'Available')
            {
              return 'success';
            }
            else if ($row ['status'] == 'Unavailable')
            {
              return 'danger';
            }}).'

<a href="book_details.php?title='. $row['title'].'&isbn='. $row['isbn'].'"> <button type="button"class="btn btn-'.$status.'">'. $row['status'].'</button></a>


          </div>
        </div>

      </div>';

Upvotes: 0

Nick
Nick

Reputation: 147166

You can't do that. The cleanest solution would be to put the if statement before the generation of $output i.e.

$status = $row ['status'] == 'Available' ? 'success' : 'danger';
$output .= '    <div class="col-md-3 mb-4">
    ...
          <div class="card-body">
<a href="book_details.php?title='. $row['title'].'&isbn='. $row['isbn'].'"> <button type="button"class="btn btn-'.$status.'">'. $row['status'].'</button></a>
    ...
    </div>';

For such large blocks of text, you might want to consider heredoc syntax. See this demo.

Upvotes: 3

Related Questions