How To Remove Duplicates From Array Using PHP
While working with arrays, there may have been a time when you came across duplicate values in array. In some cases, these duplicates values are undesirable and you may want to remove these duplicate values from the same array. So do you know how to remove duplicate values from array? If not then here are easy examples that show you how to use PHP to remove duplicates from array.
Using PHP to Remove Duplicate Values From Array
Let’s consider that we have an array that contains fruits names. One of the fruits is now duplicated in the array and we would like to remove this duplicated value. Consider the following array below:
$my_fruits_array = array('apple', 'mango', 'grapes', 'pineapple', 'apple', 'guava', 'apple');
As you can see in the above array, the fruit “apple” appears thrice i.e. it is duplicated twice. So now we would like to retain only the first occurrence of “apple” and remove the other two duplicate values from the array.
Example 1 – Remove duplicates from array using PHP
<?php echo 'Example 1: Removing a value from the array - Remove value "apple" <br />'; //Declare an array $my_fruits_array = array('apple', 'mango', 'grapes', 'pineapple', 'apple', 'guava', 'apple'); //Print the contents of the array. echo 'Following are the original array contents:<br />'; echo '<pre>'; print_r($my_fruits_array); echo '</pre>'; //Remove duplicated "apple" value from array $my_fruits_array_new = array_unique($my_fruits_array); //Print the contents of the array. echo 'Following are the array contents AFTER removing the duplicate values from array:<br />'; echo '<pre>'; print_r($my_fruits_array_new); echo '</pre>'; ?>
Example 2 – Delete Duplicates From Array Using PHP
<?php echo '<br />Example 2: Removing a value from the array - Remove value "grapes" <br />'; $my_fruits_array = array('apple', 'mango', 'grapes', 'pineapple', 'apple', 'guava', 'apple'); //Print the contents of the array. echo 'Following are the original array contents:<br />'; echo '<pre>'; print_r($my_fruits_array); echo '</pre>'; //Remove "apple" value from array $my_fruits_array_new = array_map('unserialize', array_unique(array_map('serialize', $my_fruits_array))); //Print the contents of the array. echo 'Following are the array contents AFTER removing the value from array:<br />'; echo '<pre>'; print_r($my_fruits_array_new); echo '</pre>'; ?>
That’s it!
Do you know of any other ways to use PHP to delete duplicate values from array? Feel free to share by commenting below.