3

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 array subarray (item) based on the today 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 like this:

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 tryed to follow suggestions from this question How to search by key=>value in a multidimensional array in PHP

but if I'm able to filter for a key = value, I'm not able to do the same using the "check_if_in_range" function.

Community
  • 1
  • 1
bluantinoo
  • 1,829
  • 3
  • 19
  • 25
  • How did you use `check_if_in_range`? – SaidbakR Apr 23 '15 at 20:12
  • as Glavić has pointed out in the answer I've pick my error was on date format. I was comparing '30/06/2015' to date('d/m/Y') in the check_if_in_range function, and it was not working. – bluantinoo Apr 27 '15 at 14:50

2 Answers2

1

You do know that 30/06/2015 is invalid date, and strtotime() will return false? See here. Format mm/dd/yyyy is an American month, day and year. So your format is non-standard.

Best way is to convert it to standard format, and then use strtotime()example or just use DateTime::createFromFormat()example.

After you learn how formating and converting dates works, then you can just do simple foreach loop, and break on first found result. Here is a little demo.

Glavić
  • 42,781
  • 13
  • 77
  • 107
-1

Try something like the following

foreach($array as $key => $value) {
    if(check_in_range($value['start'], $value['end'], $today_date)) {
        $selected_subarray = $value;
    }
}
Scott Miller
  • 332
  • 2
  • 14