Search code examples
phphtmlecho

inside the echo, why the php variable can't be printed with html tag


I have a problem printing the dynamic value in the table. The first photo is the result I want: enter image description here

The second photo is the result I got: enter image description here Here is my code:

<?php
        if(in some conditions, the table will appears with dynamic vairalbe) { 
         //some logic to get the single value, here let's assume the result is 85.00
         $single = 85.00;
         //here is the table with value
         echo '
         <table class="table table-striped"> 
            <thead>
                <tr>
                <th scope="row">Status</th> 
                <th scope="row">Tax</th> 
                </tr>
            </thead>
            <tbody>
                <tr>
                <th scope="row">Single</th>
                <td> {$single} <td>
                </tr>
                <tr>
            </tbody>
            </table>
         ';
        }
    ?>

Solution

  • The problem here are the single-quotes. They display almost everything "as-is". (Reference difference between single and double qoutes)

    If you want the variable to be parsed, you have to use double-quotes instead. (")

    Important: Don't forget to escape all the other double-quotes you want to be echoed literally.

    Example:

    <?php
    echo "
    <table class=\"table table-striped\"> 
        <thead>
            <tr>
                <th scope=\"row\">Status</th> 
                <th scope=\"row\">Tax</th> 
            </tr>
        </thead>
        <tbody>
            <tr>
                <th scope=\"row\">Single</th>
                <td> {$single} </td>
            </tr>
        </tbody>
    </table>
    ";
    ?>