BobCreativeDu
BobCreativeDu

Reputation: 39

PHP variable in div class

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.

Upvotes: 3

Views: 4861

Answers (4)

giessebi
giessebi

Reputation: 168

of course it is

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

cheers.

Upvotes: 1

Ganesh Patil
Ganesh Patil

Reputation: 670

you are doing right just write

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

Upvotes: 1

Halcyon
Halcyon

Reputation: 57709

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>

Upvotes: 2

Rajendra Yadav
Rajendra Yadav

Reputation: 635

Yes, you can use it like

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

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

Upvotes: 5

Related Questions