user1444027
user1444027

Reputation: 5241

Simple foreach search within multidimensional array

I have the following array:

$dates[] = array(
    'Sunday'  => '13 Jul 2014',
    'Monday'  => '14 Jul 2014',
    'Tuesday' => '15 Jul 2014',
);

I would like to search the array to see if there is a match with today. I have set today up as a variable as follows:

$today = date('d M Y', strtotime('today'));

And I am attempting to search for a match using a simple foreach:

foreach ($dates as $day => $date) {
    if ($today == $date) {
        echo 'match';
    } else {
        echo 'no match';
    }
}

However, this always returns 'no match'. Any ideas what I am doing wrong?

Live version here: http://viper-7.com/4INcaz

Upvotes: 0

Views: 70

Answers (1)

Jonan
Jonan

Reputation: 2536

This is your array:

array(
    0 => array(
        'Sunday'  => '13 Jul 2014',
        'Monday'  => '14 Jul 2014',
        'Tuesday' => '15 Jul 2014',
    )
);

because you assigned the array to $dates[]. You should do:

foreach ($dates[0] as $day => $date) {
    if ($today == $date) {
        echo 'match';
    } else {
        echo 'no match';
    }
}

or this:

$dates = array(
    'Sunday'  => '13 Jul 2014',
    'Monday'  => '14 Jul 2014',
    'Tuesday' => '15 Jul 2014',
);

Upvotes: 4

Related Questions