Robster Robster - 1 year ago 48
HTML Question

Include if statement in HTML table

I want to include an

if
statement in my PHP code that renders an HTML table. The output should be in a table row, too.

echo '<table style="border:1px solid red;">',
'<tr align="center" ><td><div class="item-font1">', $mounts['name'], '</div></td>
</tr>',
if ($itembind == 1) {
echo '<tr align="center" ><td><div class="item-font1">Text1</div></td>
</tr>',
} elseif ($itembind== 2) {
echo '<tr align="center" ><td><div class="item-font1">Text2</div></td>
</tr>',
echo "\t";
}
'<tr align="center" ><td><div class="item-font1">', $mounts['name'], '</div></td>
</tr>
</table>';
?>


I tried it like this, but there are some errors.

Answer Source

With echo, the strings can be separated by a comma (i.e. ,). However, when additional logic is needed, the echo statement must be terminated. Use a semi-colon (i.e. ;) for that.

echo '<table style="border:1px solid red;">',
    '<tr align="center" ><td><div class="item-font1">', $mounts['name'], 
    '</div></td>
     </tr>'; //use a semi-colon here to end the call to echo

if ($itembind == 1) { 

As in C or Perl, PHP requires instructions to be terminated with a semicolon at the end of each statement. The closing tag of a block of PHP code automatically implies a semicolon; you do not need to have a semicolon terminating the last line of a PHP block. 1

While it is acceptable to pass multiple strings to echo, the strings could be concatenated into one. For that, use a dot operator.

So update this line (which is missing an echo at the beginning) :

'<tr align="center" ><td><div class="item-font1">', $mounts['name'], '</div>
</td></tr></table>';

To

echo '<tr align="center" ><td><div class="item-font1">'. $mounts['name']. '</div>
</td></tr></table>';

Final output:

<?php
$mounts = ['name'=>'cat'];
$itembind = 1;
echo '<table style="border:1px solid red;">',
 '<tr align="center" ><td><div class="item-font1">', $mounts['name'], '</div></td>
</tr>';
 if ($itembind == 1) {
    echo '<tr align="center" ><td><div class="item-font1">Text1</div></td>
</tr>';
} elseif ($itembind== 2) {
    echo '<tr align="center" ><td><div class="item-font1">Text2</div></td>
</tr>';
echo "\t";
}
 echo '<tr align="center" ><td><div class="item-font1">', $mounts['name'], '</div></td>
</tr>  
</table>';
?>

See a demonstration of the updated code in this playground example.


1http://php.net/manual/en/language.basic-syntax.instruction-separation.php

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download