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.
So, I read this, but it doesn't say which value is a duplicate.
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.";
}