skip to Main Content

I’m trying to change the visibility for a span class in a PHP file based on a variable (string) I defined earlier. I want to make the span class hidden or invisible if the variable (string) is empty. I know the span class has the attribute hidden but I can’t figure out how to make this attribute conditional on whether the string is empty.

<?php $str = "Hello!"; // this string can be empty as well ?>y

<span class="tooltiptext"><?php echo $str;?></span>

Please look at the description above

2

Answers


  1. Since empty strings are evaluated to false, you can use a ternary operator to check this and then apply your required class.

    https://www.geeksforgeeks.org/php-ternary-operator/

    Login or Signup to reply.
  2. Use an if statement.

    if (empty($str)) { ?>
        <span class="tooltiptext hidden"></span>
    <?php } else { ?>
        <span class="tooltiptext"><?php echo $str;?></span>
    <?php }
    

    Then use CSS to change the style of .tooltiptext.hidden.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search