Remove duplicates from array PHP
In this post, you will learn how to remove duplicates from an array using the PHP programming language.
Sometimes in the development process, we may face a situation where we need to filter arrays to remove duplicates. There are lots of ways to remove the duplicate values. But, PHP provides a simple in-built function, array_unique() to remove the duplicate values from an array.
Likewise, according to this function, two elements are viewed as equivalent if and only if (string) $element1 === (string) $element2, i.e., when the string representation of the elements is the same.
Syntax of array_unique()
array_unique(array, sorttype)
Here, the array is a required parameter, and sorttype is an optional parameter. It specifies how to compare the array elements/items. The possible values are-
- SORT_STRING- Compare items as strings
- SORT_REGULAR- Compare items normally
- SORT_NUMERIC- Compare items numerically
- SORT_LOCALE_STRING- Compare items as strings
It takes a SORT_STRING value by default, which compares items as strings. This function returns a new array without duplicate values. If two or more array values are similar, the first appearance will be kept and the other will be eliminated.
PHP remove duplicates from array
In the given PHP program, we have defined the repeated values one-dimensional array. We have passed this array to the array_unique() function to remove the duplicate values.
<?php
$fruits = array('Apple', 'Orange', 'Apple', 'Banana', 'Kiwi', 'Orange');
$result = array_unique($fruits);
print_r($result);
?>
Output of the above code:
Array ( [0] => Apple [1] => Orange [3] => Banana [4] => Kiwi )
PHP remove duplicates from associative Array
In the given PHP program, we remove the duplicate values from associative array. In this, the key and value of the first appearance will be retained.
<?php
$state = ['a' => 'JH',
'b' => 'DL',
'c' => 'HR',
'f' => 'MH',
'd' => 'DL',
'e' => 'JH',
'g' => 'JK',
'h' => 'UP'];
$output = array_unique($state);
print_r($output);
?>
Output of the above code:
Array
(
[a] => JH
[b] => DL
[c] => HR
[f] => MH
[g] => JK
[h] => UP
)
Related Articles
PHP reverse a string without predefined functionPHP random quote generator
PHP convert string into an array
PHP remove HTML and PHP tags from string
Import Excel File into MySQL using PHP
PHP array length
Import Excel File into MySQL Database using PHP
PHP String Contains
PHP remove last character from string
PHP random quote generator
PHP calculate percentage of total
PHP sanitize input for MySQL
Display PDF using an AJAX call
How to fetch data from database in php and display in pdf
How to read CSV file in PHP and store in MySQL
How to create a doc file using PHP
PHP SplFileObject Examples
How to Upload a File in PHP
Sending HTML form data to an email address