Select SubArray if today date is between two key values

I have a multidimensional array like this:

$array = array(
    0 => array(
        'name' => 'first element',
        'start' => '30/04/2015',
        'end' => '30/06/2015'
    ),
    1 => array(
        'name' => 'second element',
        'start' => '01/07/2015',
        'end' => '30/09/2015'
    ),
    2 => array(
        'name' => 'fourth element',
        'start' => '01/10/2015',
        'end' => '15/12/2015'
        )
);

      

I need to select one subar (element) of an array based on today's date. today date must be between start date and end date keys.

In the end, I would like to have this:

$selected_subarray = array (
        'name' => 'first element',
        'start' => '30/04/2015',
        'end' => '30/06/2015'
    )

      

I use to check between two dates, for example:

function check_if_in_range($start_date, $end_date, $today_date)
{
  $start_d = strtotime($start_date);
  $end_d = strtotime($end_date);
  $today_d = strtotime($today_date);
  return (($today_d >= $start_d) && ($today_d <= $end_d));
}

      

I tried to follow the suggestions on this question How to search by key => value in a multidimensional array in PHP

but if I can filter the key = value, I cannot do the same with check_if_in_range function.

+3


source to share


2 answers


Do you know what 30/06/2015

is an invalid date and it strtotime()

returns false

? See here . The format mm/dd/yyyy

is the American month, day, and year. So your format is non-standard.

The best way is to convert it to standard format and then use strtotime()

an example or just use DateTime::createFromFormat()

an example .



Once you know how date formatting and converting works, you can simply do a simple foreach loop and break the first result it finds. Here's a quick demo .

+1


source


Try the following:



foreach($array as $key => $value) {
    if(check_in_range($value['start'], $value['end'], $today_date)) {
        $selected_subarray = $value;
    }
}

      

-1


source







All Articles