2

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

1 Answer 1

2

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;
                  });
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.