RHK-S8
RHK-S8

Reputation: 329

PHP Remove subarray from main array if specific value range is found

Lets say I have the following array:

  [9] => Array
    (
        [0] => Bob Smith
        [1] => [email protected]
        [2] => Helsinki
        [3] => 10
        [4] => 34
        [5] => 2014-05-12
    )

[10] => Array
    (
        [0] => John Smith
        [1] => [email protected]
        [2] => some values
        [3] => 9
        [4] => 67
        [5] => 2014-05-15
    )

[11] => Array
    (
        [0] => Clarke Kent
        [1] => [email protected]
        [2] => Crystal
        [3] => 9
        [4] => 89 
        [5] => 2014-05-16
    )

What if i want to remove a subarray when the date falls outside a specific range. So if i say wanted to find data where the date is between 2014-05-14 and 2014-05-28. Then the (new) array would print the following:

 [10] => Array
    (
        [0] => John Smith
        [1] => [email protected]
        [2] => some values
        [3] => 9
        [4] => 67
        [5] => 2014-05-15
    )

[11] => Array
    (
        [0] => Clarke Kent
        [1] => [email protected]
        [2] => Crystal
        [3] => 9
        [4] => 89 
        [5] => 2014-05-16
    )

I thought something like the following:

 foreach ($array as $row) {
     if($row[5] >= '2014-05-14' && $row[5] <= '2014-05-14') {
    // Do Something // e.g. unset subarray?
  }

}

OR should i approach it differently and iterate through the array and if a subarray matches my criteria create a new array. The result being an array with subarrays that contain dates that meet my date range. I hope this makes sense, i am trying to find the most efficient way to do this.

Thanks

Upvotes: 2

Views: 275

Answers (1)

dave
dave

Reputation: 64687

For the use case described, I would personally use array_filter:

$start_date = DateTime::createFromFormat('Y-m-d', '2014-05-14');
$end_date = DateTime::createFromFormat('Y-m-d', '2014-06-14');

$filtered_array = array_filter($array, function($row) use ($start_date, $end_date) {
                      $date = DateTime::createFromFormat('Y-m-d', $row[5]);
                      return $date >= $start_date && $date <= $end_date;
                  });

Upvotes: 2

Related Questions