PHP Unique Array Values

In this guide I will show you how to get unique array values in PHP. The is really easy to do and can be useful for many reasons while coding. For example, if you want to identify what values are in the array, but you don’t want to look at all the data. Another example could be you want to use existing data to drive the future selections. In this case I might take the colors that users have selected, unique the values, then create a drop down on my page from it. The possibilities are endless and would love to hear why you use unique data in the comments below.

First we need to establish an array that has some duplicate values in it. As an example we can use this colors array.

# Define the array colors we want to make unique
$colors = array("green", "blue", "orange", "yellow", "red", "green", "green", "blue");

In order to get the unique values from the $colors array we will use a native PHP function called array_unique().

# Get the unique color values
$unique_colors = array_unique($colors);

So now that we have gotten the unique values from the array, we can do whatever we want with this revised data. In this case I will print the data to verify we got the expected results.

# Print out the unique color values
print_r($unique_colors);

The results will now look like this. We can see the duplicate(s) were removed.

Array  (
      [0] => green
      [1] => blue
      [2] => orange
      [3] => yellow
      [4] => red  
)

The full code might look something like below when we put it all together. There are many different use cases for trying to get unique data. If you are having troubles or want to share what projects you work on that requires unique data, please drop a comment below!

<?php
# Define the array colors we want to make unique
$colors = array("green", "blue", "orange", "yellow", "red", "green", "green", "blue");

# Get the unique color values
$unique_colors = array_unique($colors);

# Print out the unique color values
print_r($unique_colors);
?>

Leave a Comment