DEV Community

Ismail
Ismail

Posted on

Generate Dynamically months array in PHP

if date is 2023-02-07 then run only till to feb
if date is 2022-06-12 then run loop only till to June if date is 2022-12-31 then run till to dec

$selected_date= "02/07/2022" // d/m/Y
$selected_month_number = date('n', strtotime($selected_date));
$selected_year = date('Y', strtotime($selected_date));

$months = array();

for ($i = 1; $i <= $selected_month_number; $i++) {
    $month_name = date('M', strtotime("$selected_year-$i-01"));
    array_push($months, $month_name);
}
 print_r($months);
//  Out put will be Array ( [0] => Jan [1] => Feb )
Enter fullscreen mode Exit fullscreen mode

Top comments (0)

👋 Kindness is contagious

Dive into this thoughtful article, cherished within the supportive DEV Community. Coders of every background are encouraged to share and grow our collective expertise.

A genuine "thank you" can brighten someone’s day—drop your appreciation in the comments below!

On DEV, sharing knowledge smooths our journey and strengthens our community bonds. Found value here? A quick thank you to the author makes a big difference.

Okay