How to remove duplicate values from an array in PHP?
Answer: Using array_unique()
function
We can remove the duplicate values from the array using the PHP array_unique()
function. If any value is present more than once, then this function will keep the first occurrence and remove all the remaining duplicates.
The function takes an array as its value and returns a new array with zero duplicate values.
Example: Removing duplicate values from an array
In the given example, we have removed the duplicate values from the array using PHP predefined function array_unique()
function.
<!DOCTYPE html>
<html>
<head>
<title>Removing duplicate values from an array </title>
</head>
<body>
<?php
$array = array("HTML", "CSS", "JavaScript", "PHP", "jQuery", "PHP", "HTML");
$new_array = array_unique($array);
print_r($new_array);
?>
</body>
</html>
Array ( [0] => HTML [1] => CSS [2] => JavaScript [3] => PHP [4] => jQuery )
Removing Using foreach
loop
We can also remove duplicate values from an array without using the PHP function. Here, we will iterate the array using the foreach
loop and then using the in_array()
function. We have removed the duplicate values from the array.
Example: Remove duplicate values from an array
In the given example, we have removed the duplicate values from the given array using the foreach
loop.
<!DOCTYPE html>
<html>
<head>
<title>Removing duplicate values from an array </title>
</head>
<body>
<?php
$array = array("HTML", "CSS", "JavaScript", "PHP", "jQuery", "PHP", "HTML");
$result = [];
foreach($array as $key => $arrVal) {
if(!in_array($arrVal, $result)){
array_push($result, $arrVal);
}
}
print_r ($result);
?>
</body>
</html>
Array ( [0] => HTML [1] => CSS [2] => JavaScript [3] => PHP [4] => jQuery )
Conclusion
In this lesson, we have learned how to remove duplicate values from an array in PHP. Here, we have discussed two methods with the help of which we can remove the duplicate values from an array. At first, we used the array_unique()
function, a predefined PHP function that removes the array duplicate values from the array. Then we have removed the duplicate values from the array using the foreach
loop.