Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

Sinres's avatar

How to orderby desc date in foreach loop

Hello !

I want to display my date array in descending order. How I can do this? Only by collection function where is orderBy? This is my code and array:

$dates = [];
        $period = CarbonPeriod::create($start_date->subMonths(12), '1 month', $end_date);

        foreach ($period as $date) {
            $dates[] = $date->format("Y-m");
        }

        $result = [];
        foreach ($dates as $date) {

                $result[] = [
                    'date' => $date,
                ];
        }
        return $result;
[
    {
        "date": "2020-11"
    },
    {
        "date": "2020-12"
    },
    {
        "date": "2021-01"
    },
    {
        "date": "2021-02"
    },
    {
        "date": "2021-03"
    },
    {
        "date": "2021-04"
    },
    {
        "date": "2021-05"
    },
    {
        "date": "2021-06"
    },
    {
        "date": "2021-07"
    },
    {
        "date": "2021-08"
    },
    {
        "date": "2021-09"
    },
    {
        "date": "2021-10"
    },
    {
        "date": "2021-11"
    }
]

Thanks!

0 likes
2 replies
Sinnbeck's avatar
Sinnbeck
Best Answer
Level 102

so just in reverse?

foreach (array_reverse($dates) as $date) {

                $result[] = [
                    'date' => $date,
                ];
        }
        return $result;
1 like

Please or to participate in this conversation.