1

I have an array with timestamps. If this timestamps are between two given dates I need to collect them into another array. Let me use an example:

Lets say $array1[] has:

Array ( [0] => 1299147500 [1] => 1299147453 [2] => 1299146476 [3] => 1299143220 [4] => 1297934349 [5] => 1297845742 [6] => 1297695551 [7] => 1296134251 [8] => 1295948452 [9] => 1295554308 [10] => 1295369389 [11] => 1295345559 [12] => 1295261432 [13] => 1295014784 [14] => 1294929846 [15] => 1294832875 )

I need to create $array2[] with those values from $array1[] that are between Thursday February 17, 2011 and Thursday March 3, 2011 How can I do this?

Thanks a ton

user638009
  • 223
  • 1
  • 9
  • 25
  • Use a `for` loop and check each element in `$array1` if it is between your desired dates, then add it to `$array2` if that is the case ? This should be quite basic, therefore I do not see what was causing trouble for you, or did I understand your question wrong ? To convert time specs like `Thursday February 17, 2011` to timestamps, use `strtotime()`. – Arc Apr 18 '11 at 12:23

4 Answers4

2
$low = strtotime('Thursday February 17, 2011');
$high = strtotime('Thursday March 3, 2011');

$array2 = array();
foreach($array1 as $timestamp) {
    if ($low <= $timestamp && $timestamp <= $high) {
        $array2[] = $timestamp;
    }
}

an alternative using array_filter which will maintain the keys.

$low = strtotime('Thursday February 17, 2011');
$high = strtotime('Thursday March 3, 2011');

$array2 = array_filter($array1, function($timestamp) use ($low, $high) {
    return $low <= $timestamp && $timestamp <= $high;
});
Jacob
  • 8,278
  • 1
  • 23
  • 29
2
  1. Convert first and last date to timestamps using strtotime()
  2. For each item in the array, if it is between min and max, copy it to the second array. Sort the array of timestamps
Charles Brunet
  • 21,797
  • 24
  • 83
  • 124
  • You're increasing the complexity by first sorting the timestamps. You can do it in O(n) with a single pass through the array. – Jacob Apr 18 '11 at 13:11
1

http://codepad.org/mDvRJ534

<?php
$array1 = array(1299147500,1299147453,1299146476,1299143220,1297934349,1297845742,1297695551,1296134251,1295948452,1295554308,1295369389,1295345559,1295261432,1295014784,1294929846,1294832875);
$array2 = array();
$date1 = strtotime('Thursday February 17, 2011');
$date2 = strtotime('Thursday March 3, 2011');
foreach($array1 as $timestamp){
    if($timestamp <= $date2 && $timestamp >= $date1)
        $array2[] = $timestamp;
}
echo 'date1 = '.$date1."\n";
echo 'date2 = '.$date2."\n";
print_r($array2);
Shikiryu
  • 10,180
  • 8
  • 49
  • 75
  • Thanks a ton, it may be it, but in the output, $array2[] contains timestamps that are lower than $date1. $date1 = 1297897200 and $array2: .. [2] => 1297695551 [3] => 1296134251 [4] => 1295948452 ... – user638009 Apr 18 '11 at 13:25
0

Someone answered this in another post over here mate How to check if a date is in a given range?

Community
  • 1
  • 1