Ty Yt Ty Yt -5 years ago 129
MySQL Question

Check if multiple dates are the same in foreach

I have an "Events" table in MySQL :

I'd like to check if multiple events have the same start date to show it differently in my HTML template.
My SQL request is :

SELECT * FROM EVENTSDATE where event='$id' and start_date>='$today' order by start_date asc

Now my foreach :

foreach ($upcomingDates as $value) { //$upcoming is the array with my sql request


How can I say : "if you find two rows with the same start_date, echo something"

Thanks !

Answer Source

I have a slightly different approach.

// Array to contain all values
$container = array();

// Loop through your existing array
foreach ($upcomingDates as $key => $value) {
    // Check if the value is already in the container array
    // If this is the case, its a duplicate.
    if (array_key_exists($value['start_date'], $container)) {
        echo $value.' is a duplicate with key '.$key;

    // Add each value to the array
    $container[$value['start_date']] = 1;

Another method is to use array_count_values()

foreach(array_count_values($upcomingDates) as $value => $c) {
    if ($c > 1) {
        echo $value.' is a duplicate';

Note that the second option won't work if your $upcomingDates is an array of arrays.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download