jesse94 jesse94 - 1 year ago 59
PHP Question

How to get distinct months from array containing dates

I have an array with dates. ie.

array(
0 => '2016-08-01',
1 => '2016-07-15',
2 => '2016-07-01'
);


I need to get the distinct months in array. I need to loop in the months names. ie.

array(
0 => 7,
1 => 8
);

Answer Source

You can reformat the date using a combination of array_map, DateTime, and array_unique to achieve that result.

$arr = array(
    0 => '2016-08-01',
    1 => '2016-07-15',
    2 => '2016-07-01'
);
$dates = array_unique(array_map(function($date) {
    return DateTime::createFromFormat('Y-m-d', $date)->format('n');
}, $arr));

var_dump($dates);
array(2) {
  [0]=>
  string(1) "8"
  [1]=>
  string(1) "7"
}

Of course, it's important to note this results in two dates like 2015-08-11 and 2016-08-04 both showing up as one value in the array. So it's not entirely clear why you would want to do this, but this will meet your specified requirements.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download