简体   繁体   中英

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

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',
);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM