Austin
Austin

Reputation: 3080

Add "border" to table within echo statement

So I just built a table via a PHP statement, but I am not sure how to add a border="1" attribute as that messes up the echo statement and causes compile errors.

Here is my code, yes it looks scary in this format, but I just need to give the table a border tag somehow.!

echo 
"<table><tr>
<th></th>
<th>A</th>
<th>B</th>
<th>AB</th>
<th>O</th>

</tr><tr>

<th>N</th>
<th>" . $ATypeN . "</th>
<th>" . $BTypeN . "</th>
<th>" . $ABTypeN . "</th>
<th>" . $OTypeN . "</th>
<th>". 

"</tr><tr>

<th>Y</th>
<th>" . $ATypeY . "</th>
<th>" . $BTypeY . "</th>
<th>" . $ABTypeY . "</th>
<th>" . $OTypeY . "</th>
</tr>
</table>";

Upvotes: 0

Views: 19961

Answers (2)

Patrick Moore
Patrick Moore

Reputation: 13344

You need to escape the quotes with a \ (backslash) immediately before the quote characters, like:

echo "<table border=\"0\"><tr>";

You can also use single quotes within double quotes, or vice versa, like:

echo '<table border="0"><tr>';

or:

echo "<table border='0'><tr>";

Commenter points out the HEREDOC method, which may be of great value to you as well. Start and end with the same identifier:

/* start with "EOT", must also terminate with "EOT" followed by a semicolon */

echo <<<EOT 
<table><tr>
<th></th>
<th>A</th>
<th>B</th>
<th>AB</th>
<th>O</th>

</tr><tr>

<th>N</th>
<th>$ATypeN</th>
<th>$BTypeN</th>
<th>$ABTypeN</th>
<th>$OTypeN</th>
</tr><tr>

<th>Y</th>
<th>$ATypeY</th>
<th>$BTypeY</th>
<th>$ABTypeY</th>
<th>$OTypeY</th>
</tr>
</table>
EOT; /* terminated here, cannot be indented, line must contain only EOT; */

Upvotes: 5

mrjamesmyers
mrjamesmyers

Reputation: 494

Although the above answer points out your error there a couple of things which should be pointed out.

If you were using single quotes you would not need to escape your double quotes:

So

echo '<table border=\"0\"><tr>';

should be

echo '<table border="0"><tr>';

Also using single quotes and commas to concatenate stings has faster execution time than using double quotes and periods; everything in double quotes gets evaluated.

so you could also do

echo '<table><tr><td>',$someValue,'</td></tr></table>';

Another way you could also do it would be to write out the HTML and then echo out the variables like below, where you would have the benefit of syntax highlighting your HTML in your text editor.

<table>
    <tr>
        <td><?php echo $someValue ?></td>
    </tr>
</table>

or with PHP Short tags enabled (which I'm not a fan of)

<table>
    <tr>
        <td><?=$someValue ?></td>
    </tr>
</table>

Upvotes: 1

Related Questions