Remove duplicate values from an array in PHP

By Faruque Ahamed Mollick

In this post, we are going to see how to remove the duplicate values from an array in PHP. It may be necessary for many times to take only unique values from an array by removing all the duplicate values. Here we are going to do it using PHP.

In PHP there is a function which is array_unique() function. Using this array_unique() PHP function we can remove the duplicate values from an arrray.

Below is the syntax of PHP array_unique function:

array_unique(array)

We just have to pass our array as a parameter to the array_unique function and it will return us an array without duplicate values.



Merge Multiple Arrays Into one Array Using PHP array_merge() Function

Easy to use PHP function to show a random image from a particular directory

Now see an example.

Suppose we have an array that is given below:

Array
(
    [shirt] => red
    [pant] => blue
    [jacket] => red
    [shoes] => blue
)

Now we are going to remove the duplicate items or values from the array. below is our code that will do that:

<?php
  $arr = array(
  	  'shirt' => 'red',
  	  'pant' => 'blue',
  	  'jacket' => 'red',
  	  'shoes' => 'blue'
  	);

  $arr_uniq = array_unique($arr);
  echo "<pre>"; print_r($arr_uniq); echo "</pre>";

?>

Now the above code will return the result that is given below:

Array
(
    [shirt] => red
    [pant] => blue
)

In the above array, we can see that the array items containing duplicate values removed from the array and we can see if there are any duplicate values in the array, only the first one is taken.

So we are able to remove all the duplicate values from an array and return only unique values using PHP array_unique() function.

Leave a Reply

Your email address will not be published. Required fields are marked *