Find a unique value in an array???

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
User avatar
azycraze
Forum Commoner
Posts: 56
Joined: Mon Oct 24, 2011 12:08 pm
Location: India

Find a unique value in an array???

Post 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??
Eric!
DevNet Resident
Posts: 1146
Joined: Sun Jun 14, 2009 3:13 pm

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

Post 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]
Post Reply