Combine three strings (day, month, year) and calculate next date PHP?

In PHP, you can combine three separate strings representing day, month, and year to form a complete date, then calculate the next date from a given set of date components. This is useful when working with date arrays or when you need to find the next available date from predefined options.

Combining Date Components

The most efficient approach is to iterate through arrays of years, months, and days using nested loops to find the next date greater than a given reference date −

<?php
$givenDate = '2018-04-28';
$fiveYears  = '2018,2019,2020,2021,2022'; 
$fiveMonths = '03,05,07,08,09';
$fiveDays   = '25,26,27,28,29';

$fYears = explode(',', $fiveYears);
$fMonths = explode(',', $fiveMonths);
$fDays = explode(',', $fiveDays);

$nextDate = null;

foreach($fYears as $yr) {
    foreach($fMonths as $mn) {
        foreach($fDays as $dy) {
            $t = $yr.'-'.$mn.'-'.$dy;
            if($t > $givenDate) {
                $nextDate = $t;
                break 3;
            }
        }
    }
}

if($nextDate) {
    echo 'The next date value is = ' . $nextDate;
} else {
    echo 'No date is found.';
}
?>
The next date value is = 2018-05-25

How It Works

The code uses three nested foreach loops to iterate through all possible combinations of years, months, and days. When a date combination is found that is greater than the given reference date, it immediately breaks out of all three loops using break 3 and stores the result.

Alternative Using DateTime

For more robust date handling, you can use PHP's DateTime class −

<?php
$givenDate = new DateTime('2018-04-28');
$years = [2018, 2019, 2020];
$months = [3, 5, 7, 8, 9];
$days = [25, 26, 27, 28, 29];

$nextDate = null;

foreach($years as $year) {
    foreach($months as $month) {
        foreach($days as $day) {
            $currentDate = new DateTime("$year-$month-$day");
            if($currentDate > $givenDate) {
                $nextDate = $currentDate->format('Y-m-d');
                break 3;
            }
        }
    }
}

echo $nextDate ? "Next date: $nextDate" : "No date found";
?>
Next date: 2018-05-25

Conclusion

Both methods effectively combine date components and find the next available date. The DateTime approach offers better date validation and formatting options, while the string concatenation method is simpler for basic date comparisons.

Updated on: 2026-03-15T09:36:29+05:30

624 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements