Unique value

if I have an array and want to select the unique values in php:
$array_a = array(1=>100,5=>150, 8=100, 12=>300)

i want use function return value

[0]=150
[1]=300

and Not retrieve the value[100]

or function retrieve value[100] and not retrieve the others

if i used array_unique it will retrive these value
[1]=100
[5]=150
[12]=300

There are lots of different ways of doing this, but as you have seen array_unique() is not what you want.

One way would be to count how many occurrences of each value exist in the array, then either keep values that appear just once (your “unique” values) or multiple times. Two different methods of getting those values in PHP are below.


<?php
$array  = array(100, 150, 100, 300);
foreach (array_count_values($array) as $value => $count) {
	if ($count === 1) {
		$ones[] = $value;
	} else {
		$dups[] = $value;
	}
}
var_dump($ones, $dups);
?>


<?php
$array  = array(100, 150, 100, 300);
$counts = array_count_values($array);
$ones   = array_keys(array_filter($counts, function ($value) { return $value === 1; }));
$dups   = array_keys(array_filter($counts, function ($value) { return $value > 1; }));
var_dump($ones, $dups);
?>

Of course if you only want the “unique” values, or only want the non-“unique” values, then you can skip building the unneeded array. The key part to both of the above code snippets is using array_count_values() to count how many times each value occurs in the array.

I did it this way.


<?php
$array  = array(100, 150, 100, 300);
$cond = array_diff($array,array_diff_assoc($array,array_unique($array)));
var_dump($cond); //array(2) { [1]=> int(150) [3]=> int(300) } 

The idea is:
Associatively Diff the array and it’s Unique counterpart, which gives you the non-unique values, then Diff the original array with the non-uniques, and you get the uniques.