I have an Array of Timestamps (as key) and Strings (as value).
I would like to get all the elements of the Array, where the Timestamp is in a specific Month.
E.g: 2015-April: from 0:00 1th of April 2015, until 23:59 30th of April 2015.
What is the best method for that? Shall i sort my array first with ksort
, or that makes it slower?
EDITED: Dump of my array:
array(327) { [1428226200]=> string(95) "foo" [1428231600]=> string(95) "bar" ... }
I also can get an array like this easily, if it's better:
array(327) { ["2014/03/05 09:30"]=> string(95) "foo" ["2015/04/07 11:00"]=> string(95) "bar" ... }
Convert the timestamps to a date and compare against the formatted month:
$dates = /* your array */
$aprilDates = [];
foreach ($dates as $timestamp => $value) {
$date = new \DateTime("@$timestamp");
if ($date instanceof \DateTime && $date->format('m') == 4) {
$aprilDates[$timestamp] = $value;
}
}
Instead of \DateTime
, you can also use the date
function:
foreach ($dates as $timestamp => $value) {
if (date('m', $timestamp) == 2) {
$aprilDates[$timestamp] = $value;
}
}
Yet another option:
$startDate = strtotime('first day of April');
$endDate = strtotime('last day of April 23:59:59');
foreach ($dates as $timestamp => $value) {
if ($timestamp >= $startDate && $timestamp <= $endDate) {
echo $value, PHP_EOL;
}
}
Regarding your question
Shall i sort my array first with ksort, or that makes it slower?
Sorting the array first will do one additional iteration over the array. That means yes, it will be slower. With only a few hundreds items in there, it will likely make no noticeable difference though.