OneBite.Dev - Coding blog in a bite size

Remove Duplicates From An Array In PHP

Code snippet for how to Remove Duplicates From An Array In PHP with sample and detail explanation

In programming, data management is a crucial factor to obtain accurate results. This task often involves removing redundancy, such as removing duplicates from arrays. In PHP, this can be achieved using built-in functions that the language provides.

Code snippet: Using array_unique()

The array_unique() function is a built-in function in PHP that is used to remove duplicate values from an array. The below code snippet does this effectively:

<?php
$originalArray = array("apple", "banana", "apple", "pear", "banana", "cherry");
$filteredArray = array_unique($originalArray);

print_r($filteredArray);
?>

Code Explanation for Using array_unique()

The code above is quite simple to understand. In the very first statement, we have declared our own PHP array $originalArray with some duplicate items in it. The next line is where we actually remove these duplicate values from our array.

The array_unique() function takes one array as its input, which is the array from which we want to remove duplicate values. Here, it’s our $originalArray. The function returns a new array that contains no duplicate values. We store this new array in the variable $filteredArray.

Lastly, we use print_r() function to print our newly created array, $filteredArray, to the screen. As opposed to the original array, this array doesn’t contain any duplicate items.

This is a simple yet efficient way of removing duplicate values from an array in PHP. However, It’s worth noting that array_unique() is not the most efficient way to remove duplicates from large arrays, as it has a complexity of O(n^2) in the worst-case scenario. For larger datasets, you might want to consider using other methods or sorting the array first.

php