简体   繁体   中英

PHP echo when empty doesn't work

I'm trying to hide a table row whenever $visible is not empty:

<?php
$visible = "yes";  // hide the row if different than "0"
?>
<HTML>
//Big HTML Block
<tr<?= !$visible ? "" : "class=\"hidden\""; ?>>

but my output is:

<tr>

instead of:

<tr class="hidden">

What's wrong? and is there a better way to do what I'm trying to do here? I do it this way basically since I want to define right at the top of the code, whether that <TR> that comes after a lot of HTML code, will be visible or not. It's a sort of a template that I'm creating.

"yes" is a string, not a boolean value. So as long as the string isn't empty (or the special case "0" ), php interprets this as true . And so !$visible = !true = false . So the second branch in the ternary condition is chosen. In any case, your logic appears to be backwards. Try using boolean true in place of the string "yes" and remove the ! .

<?php
$visible = true;
?>
<HTML>
//Big HTML Block
<tr<?= $visible ? "" : " class=\"hidden\""; ?>>
    <?php
    $visible = true;  // hide the row if different than "0"
    ?>
    <HTML>
    //Big HTML Block
    <tr<?php if($visible)
    echo "class=\"hidden\"";
    else
    echo ""; ?>>

You have to check if it is "yes"

<?= $visible == "yes" ? "show" : "" ?>

Or set the value to an boolean like

$visible = true

I'm still learning, but I find evaluating a conditional is easier to read if you write without the !condition. Also, use "" around '' rather than escaping each quote. Try that code, I may be missing something.

    <?php
        $invisible = true;  // hide the row if different than "0"
    ?>

    <tr class="<?= $invisible ? 'hidden' : ''; ?>">
       #stuff
    </tr>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM