2

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>
5
  • 1
    You need to use strtotime to compare the date. Or use DateTime class for the variable Commented Feb 12, 2016 at 5:56
  • 1
    and if current date is 16-02-25 than chose 16-02-28 ?? or is just a typo error?? $date or $dates? Commented Feb 12, 2016 at 6:04
  • @devpro what do you mean and if current date is 16-02-25 than chose 16-02-2 is there something that could go wrong with this code on a specific date you can see? Commented Feb 12, 2016 at 6:20
  • @LewisTyler: if current date is 16-02-12 than what value to be selected from array???? Commented Feb 12, 2016 at 6:23
  • well , u need to select last latest date? m i right? Commented Feb 12, 2016 at 6:35

1 Answer 1

1

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>";
    }
Sign up to request clarification or add additional context in comments.

1 Comment

You are using $date instead of $dates.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.