1

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.

4 Answers 4

2

"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\""; ?>>
Sign up to request clarification or add additional context in comments.

3 Comments

if it stems from being a string, why did it work for me in this case? Also, I tried your method and it still doesn't work..
The primary reason the results seem backwards is because of the misplaced !. Using a string for a true/false/yes/no/on/off type variable instead of a boolean just confuses the issue. If you coded it up such that "yes" produces the desired result, one might reasonably expect that "no" produced the opposite result but it won't work because both "yes" and "no" evaluate to boolean true when used in conditionals. Eliminate confusion and use a boolean instead.
@rockyraw. I just tested my code. Toggling $visible between true and false produces <tr> and <tr class="hidden">, respectively. Are you sure you're testing the right block of code?
0
    <?php
    $visible = true;  // hide the row if different than "0"
    ?>
    <HTML>
    //Big HTML Block
    <tr<?php if($visible)
    echo "class=\"hidden\"";
    else
    echo ""; ?>>

Comments

0

You have to check if it is "yes"

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

Or set the value to an boolean like

$visible = true

Comments

0

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>

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.