How to Remove Duplicate Values from an Array in PHP

There is an inbuilt function in PHP named array_unique() that help to remove duplicate values from an array. If you want to remove duplicate values from an array, use the array_unique() function in PHP.

Here is an array that has some duplicate values:

array('PHP', 'MySQL', 'PHP', 'JavaScript')

The following code will remove all duplicate values from an array using PHP array_unique() function:

$array = array('PHP''MySQL''PHP''JavaScript'); 
$result array_unique($array);

The result array will have the values like the below:

Array ( [0] => PHP [1] => MySQL [3] => JavaScript )

Now, we will show you how to remove duplicate values with case/space insensitively from an array in PHP.

If an array has duplicate values with a combination of upper/lower/word cases, the values need to be converted in the same latter case before applying the array_unique(). Also, we need to remove the space from values before duplicate comparison.

The following code snippet removes duplicate values from the array with case and space insensitively using PHP array_map() and array_unique() functions.

  • Remove space from all strings in an array using the trim callback method with the array_map() function.
  • Convert array values to lowercase using the strtolower callback method with the array_map() function.
  • Use array_unique() function to remove duplicate values from array with PHP.
  • Finally, use the array_intersect_key() function to return the combination of the result array.
$array = array('php ''php'' php''PHP'); 
$result array_intersect_key($arrayarray_unique(array_map('strtolower'array_map('trim'$array))));

Example:
Array values with lowercase, uppercase, and blank space:

array('php ', 'php', ' php', 'PHP')

Result array will be:

Array ( [0] => php )

Leave a reply

keyboard_double_arrow_up