如何比较多个值以找出其中是否有重复值?

huangapple go评论100阅读模式
英文:

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

使用两个嵌套循环,您可以将所有值相互比较并将重复值保存在新数组中:

  1. $input_values = array($value1, $value2, $value3, $value4, $value5, $value6, $value7, $value8);
  2. $duplicates = array();
  3. for ($i = 0; $i < count($input_values); $i++) {
  4. for ($j = $i + 1; $j < count($input_values); $j++) {
  5. if ($input_values[$i] == $input_values[$j]) {
  6. $duplicates[] = $j;
  7. }
  8. }
  9. }

最后,如果有重复项,您可以打印出来:

  1. if (count($duplicates) > 0) {
  2. foreach ($duplicates as $index) {
  3. echo $input_values[$index] . " is a duplicate.";
  4. }
  5. } else {
  6. echo "No duplicates found.";
  7. }
英文:

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

  1. $input_values = array($value1, $value2, $value3, $value4, $value5, $value6, $value7, $value8);
  2. $duplicates = array();
  3. for ($i = 0; $i &lt; count($input_values); $i++) {
  4. for ($j = $i + 1; $j &lt; count($input_values); $j++) {
  5. if ($input_values[$i] == $input_values[$j]) {
  6. $duplicates[] = $j;
  7. }
  8. }
  9. }

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

  1. if (count($duplicates) &gt; 0) {
  2. foreach ($duplicates as $index) {
  3. echo $input_values[$index] . &quot; is a duplicate.&quot;
  4. }
  5. } else {
  6. echo &quot;No duplicates found.&quot;;
  7. }

huangapple
  • 本文由 发表于 2023年5月6日 19:13:20
  • 转载请务必保留本文链接:https://go.coder-hub.com/76188556.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定