Get unique array values with PHPPosted in PHP -
The PHP function array_unique() allows you to create a new array which contains only the unique values from the original array. This post looks at some examples of using the array_unique function.
In the example below we will use an array which has been initialised with a few values as shown below:
$array = array( 'foo', 'bar', 'baz', 'bat', 'foo', 'bar', 'baz' );
The PHP function print_r() to display the values of the above array will output the following:
Array (  => foo  => bar  => foo  => baz  => bat  => bar )
As you can see from the above example, there are several duplicated values in the array, and we want to remove all the duplicated values. This is easily done as shown in the example below:
$array2 = array_unique($array); print_r($array2);
The above code will output the following, having removed the duplicated values from the array, and now only containing unique array values:
Array (  => foo  => bar  => baz  => bat )
The above example shows us the original array but with the duplicate values remove. Notice that the array keys  and  have been removed because they already contain values that featured in keys earlier in the array.
Using array_unique with an associative array
An associative array contains mixed values as the array keys, whereas the above examples use a zero based integer indexed array. The principle of the array_unique() function is the same for an associative array: any array elements with duplicated values will be completely removed from the array.
For the following example, we will use a similar array as the above, but defined with text values for the indexes and integers for the values (the exact content of the key and value do not really matter):
$array = array( 'foo' => 1, 'bar' => 2, 'foo' => 2, 'baz' => 3, 'bat' => 1, 'bar' => 3 );
Running print_r on this array will show the following:
Array ( [foo] => 2 [bar] => 3 [baz] => 3 [bat] => 1 )
Naturally, the second occurance of 'foo' and 'bar' as array keys overwrites the previous declarations in the array declaration. We can see in the above example that both 'bar' and 'baz' contain the same value of 3. So running array_unique() and then print_r() on the above array will do this:
$array2 = array_unique($array);
Array ( [foo] => 2 [bar] => 3 [bat] => 1 )
So using the PHP function array_unique() on an associative array works the same way as for a zero based integer indexed array: it makes the values of the array unique, and doesn't care about the key of the array. The key and value are completly removed from the array.