英文:
How to compare multiple values to find which one is a duplicate, if any?
问题
我有8个表单输入值(选择输入)。我希望比较它们,以确保它们之间没有一个相同。如果有重复,我希望知道是哪一个 - 如果它们是ABC,那么B是A的重复,而不是A是B的重复。
在这里,最有效的方法是什么?有效意味着代码量较少,也许?
我唯一能想到的方法是使用if-then-else。还可以将它们放入数组中并使用array_unique
。如果返回的数组项数少于原始项数,那么就存在重复。但我无法知道是哪一个。
因此,我阅读了这个,但它没有说哪个值是重复的。
英文:
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.
答案1
得分: 0
使用两个嵌套循环,您可以将所有值相互比较并将重复值保存在新数组中:
$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;
}
}
}
最后,如果有重复项,您可以打印出来:
if (count($duplicates) > 0) {
foreach ($duplicates as $index) {
echo $input_values[$index] . " is a duplicate.";
}
} else {
echo "No duplicates found.";
}
英文:
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.";
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论