Lewis Lewis - 7 months ago 50
PHP Question

Select from array next upcoming date

Okay essentially what I'm trying to achieve is grab the next upcoming date from the array. Below I have posted my array and how I select the current date.

$payout_dates = array('16-04-14','16-04-28','16-05-14');
$currentdate = date('y-m-d');


What I'm trying to do is select the next upcoming date from the array using the
current date
so for example today is
16-04-27
so the next upcoming date would be
16-04-28
Below I'm going to paste the code im using to select the next upcoming date however the only problem with changing the code below is that it is used for a
select
so having troubles just using it to echo out the date itself.

<?php
foreach ($payout_dates as $i => $d) {
if ($currentdate >= $d && ($i == count($date)-1 || $currentdate < $date[$i+1])) {
$selected = "selected";
$selected_int = $i;
} else {
$selected = "";
}
list($year, $month, $day) = explode('-', $d);
echo "<option $selected>" . date("m/d/Y", strtotime($d)) . "</option>";
}
?>


Just to reliterate the problem I'm having is selecting the next upcoming date from the current date.

BeS BeS
Answer
$payout_dates = array('16-04-14','16-04-28','16-05-14');
$currentdate = date('y-m-d');

If you don't want to convert dates using strtotime() the following might be used to select the date using string comparison since you have a lexicographical order on the dates.

$found = false;
foreach ($payout_dates as $i => $d) {
    if (! $found && strcmp($currentdate, $d) < 0) {
        $found = true;
        $selected = ' selected="selected"';
    } else {
        $selected = "";
    }
}
echo "<option $selected>" . date("m/d/Y", strtotime($d)) . "</option>";

Otherwise, you would go with the following solution:

$payout_times = array_map('strtotime', $payout_dates);
$currenttime = strtotime(date('y-m-d'));

$found = false;
foreach ($payout_times as $i => $d) {
    if (! $found && strcmp($currenttime, $d) < 0) {
        $found = true;
        $selected = ' selected="selected"';
    } else {
        $selected = "";
    }
}
echo "<option $selected>" . date("m/d/Y", $d) . "</option>";
Comments