Home » Php » php – Check if certain column has a duplicate value

php – Check if certain column has a duplicate value

Posted by: admin February 25, 2020 Leave a comment

Questions:
     Name       Number
1    Benjoe     001
2    Benjoe     002
3    Benjoe     001

Given the data, how can I determine that I found duplicate data (Row 1 and 3) using foreach? I have playing with this code right now.

Update: 02/14/2020 – I came up with this algorithm. I’ve added a flag to determine If I found a duplicate.

$results = [
    ['name' => 'Benjoe', 'number' => '001'],
    ['name' => 'Benjoe', 'number' => '002'],
    ['name' => 'Benjoe', 'number' => '001'],
]; 

foreach($results as $log) {
    if($name == $log->vlg_full_name && $number == $log->vlg_contact_number) {
        $isDuplicateNameAndNo = 1;
    } else {
        $isDuplicateNameAndNo = 0;
        break;
    }

    $name = $log->vlg_full_name;
    $number = $log->vlg_contact_number;
}
How to&Answers:

You can achieve this by a nested loop iterating throug the each element and compating it to the current one.
Try something like that:

<?php

$results = [
    ['name' => 'Benjoe', 'number' => '001'],
    ['name' => 'Benjoe', 'number' => '002'],
    ['name' => 'Benjoe', 'number' => '001'],
];

function compare($log1, $log2, $index1, $index2)
{
    return $log1['name'] == $log2['name']
        && $log1['number'] == $log2['number']
        && $index1 != $index2;
}


foreach($results as $index1 => $log1) {
     foreach ($results as $index2 => $log2) {
         if (compare($log1, $log2, $index1, $index2)) {
             echo "Item {$index1} has a duplicate at index {$index2}!<br/>\n";
         }
     }
}

Here is a link to working example on 3v4l.org

The output for the above will be:

Item 0 has a duplicate at index 2!<br/>
Item 2 has a duplicate at index 0!<br/>

If you don’t need to exactly know wich items are duplicate you can simply concatenate the values and put them into an array, and check if the value is already there:

<?php

$results = [
    ['name' => 'Benjoe', 'number' => '001'],
    ['name' => 'Benjoe', 'number' => '002'],
    ['name' => 'Benjoe', 'number' => '001'],
];

$temp = [];
foreach($results as $index => $log) {
     $val = $log['name'] . '_' . $log['number'];
     if (in_array($val, $temp)) {
         echo "Duplicate found at index {$index}<br/>\n";
     } else {
         $temp[] = $val;
     }
}

Output:

Duplicate found at index 2<br/>

Working example on 3v4l.org

If you get your $results from database, another approach would be grouping the query by the requried columns and adding the count(*) field to gind out how many records exists.