Home > Net >  how to assign a variable to a html code including an if statement in php [duplicate]
how to assign a variable to a html code including an if statement in php [duplicate]

Time:09-29

I would like to have a variable $output inside while loop containing some html and a if statement which will give class ".time_active" only to the first while loop result. I'm not able to find a way to embed if statement properly any help would be much appreciated.

$count= 0;
while($start_time < $end_time){
   $count  ;
   $output = "<label>
              <input type='radio' class='if($count == 1) {echo 'time_active';}' id='id_slot' name='time'>
               <span class='display'>span tag</span>
              </label>";
}
echo $output;

CodePudding user response:

Does this answer your question?

<?php

$count= 0;
while($start_time < $end_time){
 $count  ;
 $output = "<label><input type='radio'";
 if($count == 1){
   $output  = "class='time_active'";
 }
 $output  = "id='id_slot' name='time'><span class='display'>span tag</span></label>";
}
echo $output;

CodePudding user response:

Do not use the echo within the PHP string - create a variable before the string like so:

$count= 0;
while($start_time < $end_time){

   $count  ;
   $class=$count==1 ? 'time_active' : '';
   
   $output = "<label>
                <input type='radio' class='{$class}' name='time' />
                <span class='display'>span tag</span>
              </label>";
}
echo $output;
  • Related