PHP array unique value

We may want to get a set of unique values from an array. For this we have to use function array_unique(). This will take an array as input and return an array with unique elements of the old array.

Here is our old array with some duplicate elements.
$old_array=array("Mango","Banana","Orange","Banana"); 

$new_array=array_unique($old_array); 
Now our $new_array will contain values ("Mango","Banana","Orange")

How to check if array contains duplicate elements ?
$old_array=array("Mango","Banana","Orange","Banana"); 
if(count($old_array) != count(array_unique($old_array))){
echo " Not Unique, there are duplicate elements ";	
}else{
echo " No duplicate elements ";
}
The output is here
Not Unique, there are duplicate elements 

Getting the duplicate elements

$old_array=array("Mango","Banana","Orange","Banana"); 
$new_array=array_unique($old_array); 

// What is not common in both arrays ( keys also considered ) ///

$duplicate=array_diff_assoc($old_array,$new_array);
while (list ($key, $val) = each ($duplicate)) {
echo "$key -> $val <br>";
}
Output
3 -> Banana
Read more on array_diff_assoc()


plus2net.com




Post your comments , suggestion , error , requirements etc here .




We use cookies to improve your browsing experience. . Learn more
HTML MySQL PHP JavaScript ASP Photoshop Articles FORUM . Contact us
©2000-2020 plus2net.com All rights reserved worldwide Privacy Policy Disclaimer