Search code examples
phparraysdateformattingkey

Change date format of array keys from Y-m-d to d-m-Y


I have this array;

Array
(
    [2017-04-01] => 0
    [2017-04-02] => 0
    [2017-04-03] => 0
    [2017-04-04] => 0
    [2017-04-05] => 0
)

How can I format the date to have something like this?

Array
(
    [01-04-2017] => 0
    [02-04-2017] => 0
    [03-04-2017] => 0
    [04-04-2017] => 0
    [05-04-2017] => 0
)

Thanks.


Solution

  • A simple foreach loop then covert to format d-m-Y can do this

    $result = [];
    foreach ($datas as $key => $value) {
        $date = date('d-m-Y', strtotime($key));
        $result[$date] = $value;
    }
    
    print_r($result);