如何在 php 中比较数组值


How to compare array values in php?

我需要将数组值相互比较。这些值是唯一的 ID。因此,必须检查ID值是否重复。

<?php
 $id=array("firstid2012","secondid2014","thirddid2010","fourthid2014");
 $idcount=count($id);
 for($i=0;$i<$idcount;$i++){
 //how to compare?? 
 }  
 ?>

如果重复的 id 为真,那么我必须更改该数组值的值。所以我还需要知道哪个数组值是重复的。

if (count($idvalues) == count(array_unique($idvalues))){
  //ALL VALUES ARE DISTINCTS
}
else {
  //THERE ARE DUPLICATED VALUES
  $duplicated=array();
  $visited=array();
  foreach($idvalues as $value){
      if (in_array($value,$visited)){
         $duplicated[]=$value;
      }
      $visited[]=$value;
  }
  $duplicated=array_uniq($duplicated);
}

您感兴趣的一些功能:

array_unique:删除重复值

http://php.net/manual/en/function.array-unique.php

array_intersect :返回多个数组中出现的值。

http://php.net/manual/en/function.array-intersect.php

这是从数组中获取所有唯一值的最快方法:

$unique = array_keys(array_flip($array));

在后端,它使用哈希映射,而如果您使用array_unique,则只是遍历数组,效率非常低。差异是数量级。

您可以使用 array_unique() 获取所有唯一值的数组,然后将大小与原始数组进行比较:

if (count(array_unique($submitted_genres)) !== count($submitted_genres)) {
// there's at least one dupe
}

您无需为此运行任何循环,只需使用 array_unique(); 我添加了 fourid2014 两次

$id[] = array("firstid2012", "secondid2014", "thirddid2010", "fourthid2014", "fourthid2014");
print_r($id[0]); // print it 5 values 
$result = array_unique($id[0]);
print_r($result);// print it 4 values 

您可以使用 array_unique() 函数删除重复值请参阅此网址以获取更多信息 http://www.w3schools.com/php/func_array_unique.asp

一个简单的方法是

<?php
 $id[]=$idvalues;
 $idcount=count($id);
 for($i=0;$i<$idcount;$i++){
   for($ii=0; $ii<$idcount;$ii++)
   {
    if( $i != $ii ) //We don't want to compare the same index to itself
    {
      if( $id[$i] == $id[$ii] )
      {
        //Found same values at both $i and $ii
        //As the code is here, each duplicate will be detected twice
      }
    }
 }  
?>