phphtmlloopsdrop-down-menuselected

Create <select> options from an array of dates and make today's date or the next future date selected


Why doesn't this work, it's supposed to mark today's date or the nearest date after today. For example if the date is 16-01-30, the date chosen would be 16-02-14.

$date = ['16-01-14', '16-01-28', '16-02-14', '16-02-28'];
$currentdate = date('y-m-d');
echo $currentdate;
?>
<form>
    <select>
        <?php
        foreach ($date as $i => $d) {
            if ($currentdate >= $d && ($i == count($date)-1 || $currentdate < $date[$i+1])) {
                $selected = "selected";
            } else {
                $selected = "";
            }
            list($year, $month, $day) = explode('-', $d);
            echo "<option $selected>$month/$day/$year</option>";
        }
        ?>
    </select>
</form>

Solution

  • Here is your answer

    $dates = array('16-01-14','16-01-28','16-02-14','16-02-28');
        $currentdate = date('y-m-d');
        echo $currentdate;
        ?>
        <form>
        <select>
        <?php
        foreach ($dates as $i => $d) {
            if ($currentdate >= $d && ($i == count($dates)-1 || $currentdate < $dates[$i+1])) {
                $selected = "selected";
            } else {
                $selected = "";
            }
            list($year, $month, $day) = explode('-', $d);
            echo "<option $selected>$month/$day/$year</option>";
        }