why isn't this php loop working?
-
06-09-2019 - |
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?
Solution
Short answer: Because every single echo operation uses the current value of $sel. I assume it's initially blank, so the first N echos contain selected=''. If test succeeds, $sel is set to "selected", and every later print includes selected='selected'. If you use $perfTime = '19:30', it's an assignment, so the test always succeeds, and $sel is always 'selected'.
Quick fix: Add an else clause that sets $sel = ''. However, there are other oddities that make me think this is only a code snippit (i.e. always using $thisTime for $perfTimestamp , rather than something loop indexed, so it always prints the same time?).
OTHER TIPS
This is because you never reset $sel
.
Try this instead:
$sel = $perfTime == '19:30' ? 'selected' : '';
$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.
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>';