Horje Website
How to Remove Duplicate Values from an Array in PHP

Here is an array that has some duplicate values:

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

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

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

The result array will have the values like the below:

  1. 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.
  1. $array = array('php ', 'php', ' php', 'PHP'); $result = array_intersect_key($array, array_unique(array_map('strtolower', array_map('trim', $array))));

Array values with lowercase, uppercase, and blank space:

  1. array('php ', 'php', ' php', 'PHP')

Result array will be:

  1. Array ( [0] => php )
November 23, 2022
Full Tutorials

This article was posted in Full Tutorials. Bookmark the permalink. Follow comments with the RSS feed for this post.Post a Comment or leave a trackback: Trackback URL.

Leave a Reply

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


Horje © 2011 - 2023