Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to compare multiple values to find which one is a duplicate, if any?

I have 8 form input values (select inputs). I wish to compare them so that none is identical to another. And if there’s a duplicate, I wish to know which one – if they are ABC, then B is a duplicate of A, instead of A is a duplicate of B.

What would be the most efficient way to do this? Efficient here meaning less code, perhaps?

The only method I could think of is if-then-else. And also, put them into an array and use array_unique. If returned array item count is less than the original count, then there’s a duplication. But I can’t know which one.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

So, I read this, but it doesn’t say which value is a duplicate.

>Solution :

using two nested loop you can compare all values against each other and save the duplicates in a new array:

$input_values = array($value1, $value2, $value3, $value4, $value5, $value6, $value7, $value8);
$duplicates = array();

for ($i = 0; $i < count($input_values); $i++) {
    for ($j = $i + 1; $j < count($input_values); $j++) {
        if ($input_values[$i] == $input_values[$j]) {
            $duplicates[] = $j;
        }
    }
}

finally if there was a duplicate you can print that like:

if (count($duplicates) > 0) {
    foreach ($duplicates as $index) {
       echo $input_values[$index] . " is a duplicate."
    }
} else {
    echo "No duplicates found.";
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading