why isn't this php loop working?

Question!

I have this code:

$thisTime = gmmktime(0, 0, 0);  
            for($i=0; $i<=95; $i++)
           {  
                $perfTimeNumber = ($i+1);  
                $perfTimestamp = $thisTime;  
                $perfTime = date("H:i", $perfTimestamp);           
        echo '<option value="'. $perfTimeNumber .'" selected="'.$sel.'">' .$perfTime .'</option>';   
                $thisTime = $thisTime+(15*60);
            }

This works fine to generate a select input with options from 01:00 through to 24:45 at 15 minute intervals. However, if I change the code and add an if statement I get some odd results...

$thisTime = gmmktime(0, 0, 0);

            for($i=0; $i<=95; $i++)
            {
                $perfTimeNumber = ($i+1);
                $perfTimestamp = $thisTime;
                $perfTime = date("H:i", $perfTimestamp);
                if ($perfTime == '19:30') {
                    $sel = "selected";
                }
        echo '<option value="'. $perfTimeNumber .'" selected="'.$sel.'">' .$perfTime .'</option>';

                $thisTime = $thisTime+(15*60);
            }

The idea is to (arbitrarily!) make the select input default to 19.30. The code above adds
selected = "selected" to every option after 19:30, not just the 19:30 option. If I change the if statement slightly to be if ($perfTime = '19:30') { ... i.e., having a single = instead of == it creates a set of options all with the value of 19:30. What am I doing wrong?

By : musoNic80


Answers

Hm, might be that you should do this:

...
if ($perfTime == '19:30') {
  $sel = 'selected="selected"';
}else{
  $sel = "";  
}
...

I think just having the 'selected' attribute present makes it selected.

Oops, I forgot: And

 echo '<option value="'. $perfTimeNumber .'" '.$sel.'>' .$perfTime .'</option>';
By : 0scar


$sel isn't explicitly intitialised anywhere, so it's maintaining its 'selected' value for each run through the loop.

Try $sel = ""; as the first line in your loop as a quick fix.

By : Matt H


This is because you never reset $sel.

Try this instead:

$sel = $perfTime == '19:30' ? 'selected' : '';
By : n3rd


This video can help you solving your question :)
By: admin