简体   繁体   中英

How to compare array values in php?

I need to compare the array values with each other.These values are unique IDs. So, have to check whether ID values are repeated.

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

If repeated id is true, then i have to change the value of that array value.So I need to know which array value is repeated also.

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);
}

Some functions of interest to you:

array_unique : Remove duplicate values

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

array_intersect : Return values that occur in in more than one array.

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

This is the fastest way to get all the unique values from an array:

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

In the backend it uses a hashmap, whereas if you use array_unique that just iterates over an over the array, which is very inefficient. The difference is in orders of magnitude.

You could use array_unique() to get an array of all unique values and then compare the size against the original array:

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

You no need to run any loop for that just use array_unique(); i added fourthid2014 twice

$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

A simple way would be

<?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
      }
    }
 }  
?>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM