Page 1 of 1

Find a unique value in an array???

Posted: Wed Nov 13, 2013 12:41 am
by azycraze
Hi frnds, I have an array say

Code: Select all

$a={1 1 1 2 1 1};
I just want to get the array index of 2 since it is the only distinct value in $a.
Is there any array functions to do this??

Re: Find a unique value in an array???

Posted: Wed Nov 13, 2013 2:10 am
by Eric!
You don't want any value that has been repeated, right? Do you want to preserve the keys? If not, you could do something like this:

Code: Select all

function arrayUnique($array)
{
   $result=array();
   $duplicates=array_unique(array_diff_assoc($array,array_unique($array)));
   foreach($array as $value){
      if(!in_array($value,$duplicates)) $result[]=$value;
   }
   return $result;
}
Example:

Code: Select all

$arr1 = array('1','2','1','1','1','4');

$result=arrayUnique($arr1);
print_r($result);
[text]Array
(
[0] => 2
[1] => 4
)[/text]