3

I just want to know if it is possible to do something like this:

<?php
   if(condition1 > condition2){
       $variable = "class1";
   }else{
       $variable = "class2";
   }
?>
<div class=$variable></div>

Thanks.

2
  • 1
    Yes it possible. But for that you need to learn how PHP syntax works. Commented Jun 11, 2014 at 11:43
  • YES: <?php $variable = (condition1 > condition2)?"class1":"class2"; ?> same as in javascript. Commented Jun 11, 2014 at 11:51

4 Answers 4

5

Yes, you can use it like

    <?php
      if(condition1 > condition2){
      $variable = "class1";
      }else{
      $variable = "class2";
      }
     ?>

    <div class="<?php echo $variable; ?>" ></div>
Sign up to request clarification or add additional context in comments.

1 Comment

@user3443985 Welcome you
2

You can use short php open+echo tags:

<?php
   if(condition1 > condition2){
       $variable = "class1";
   }else{
       $variable = "class2";
   }
?>
<div class=<?=$variable;?>></div>

These are permanently enabled as of php5.4: http://www.php.net//manual/en/migration54.new-features.php

<?= is now always available, regardless of the short_open_tag php.ini option.


Make sure your HTML output is valid and standard. If $variable contains a space or html special characters you may run into issues:

<div class="<?=htmlspecialchars($variable);?>"></div>

Comments

1

you are doing right just write

<div class="<?php echo $variable; ?>" ></div>

Comments

1

of course it is

<div class="<?php echo $variable; ?>"></div>

cheers.

1 Comment

You are forgetting something.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.