Through this tutorial, we will learn how to remove duplicate elements/values from an array without using any function in PHP and also will learn how to remove elements/values from an array using inbuilt function array_unique() and array_flip() in PHP.
How to remove duplicate values from an array in PHP?
Here are some methods:
- Method 1: Using array_unique()
- Method 2: Using a loop
- Method 3: Using array_flip() and array_keys()
Method 1: Using array_unique()
The simplest way to remove duplicate values from an array in PHP is to use the built-in function array_unique(). This function takes an array as input and returns a new array with all duplicate values removed. Here’s an example:
<?php
$array = array(1, 2, 2, 3, 3, 3);
$unique_array = array_unique($array);
print_r($unique_array);
?>
The given code is written in PHP, and it creates an array named $array with the values 1, 2, 2, 3, 3, 3.
Then, the code uses the PHP built-in function array_unique()
to remove any duplicate values from the array. The unique values are then stored in a new array named $unique_array.
Finally, the print_r()
function is used to display the contents of the $unique_array.
So, the output of this code will be:
Array
(
[0] => 1
[1] => 2
[3] => 3
)
Here, the duplicate values of 2 and 3 have been removed from the original array and only unique values 1, 2, and 3 are displayed in the $unique_array.
Method 2: Using a loop
Another way to remove duplicate values from an array is to use a loop. We can iterate over the array and check if each value is already present in a new array. If the value is not present, we add it to the new array. Here’s an example:
<?php
$array = array(1, 2, 2, 3, 3, 3);
$unique_array = array();
foreach($array as $value) {
if(!in_array($value, $unique_array)) {
$unique_array[] = $value;
}
}
print_r($unique_array);
?>
Output:
Array ( [0] => 1 [1] => 2 [3] => 3 )
Method 3: Using array_flip() and array_keys()
Another way to remove duplicate values from an array is to use the array_flip() and array_keys() functions. We can flip the array, so that the values become keys, and then use the array_keys() function to get the keys. This will give us a new array with all duplicate values removed. Here’s an example:
<?php
$array = array(1, 2, 2, 3, 3, 3);
$flipped_array = array_flip($array);
$unique_array = array_keys($flipped_array);
print_r($unique_array);
?>
Output:
Array ( [0] => 1 [1] => 2 [2] => 3 )
This shows that the original array $array
contained three unique values: 1, 2, and 3.
Conclusion
In this article, we have explored various ways to remove duplicate values from an array in PHP.
Recommended PHP Tutorials
- PHP Array: Indexed,Associative, Multidimensional
- To Remove Elements or Values from Array PHP
- How to Convert String to Array in PHP
- Array Push and POP in PHP | PHP Tutorial
- PHP Search Multidimensional Array [key and value and return key]
- PHP Array to String Conversion – PHP Implode
- Array Functions In PHP – PHP Tutorial