PHP

Efficiently Remove Duplicate Values from a PHP Array

Learn how to quickly eliminate duplicate entries from a simple PHP array using the built-in array_unique function, preserving the first occurrence of each value.

<?php
$numbers = [1, 2, 2, 3, 4, 4, 5, 1];
$uniqueNumbers = array_unique($numbers);
print_r($uniqueNumbers);

$fruits = ['apple', 'banana', 'orange', 'apple', 'grape'];
$uniqueFruits = array_unique($fruits);
print_r($uniqueFruits);

// For associative arrays, it compares values and keeps the key of the first occurrence
$users = [
    'user1' => 'Alice',
    'user2' => 'Bob',
    'user3' => 'Alice',
    'user4' => 'Charlie',
];
$uniqueUsers = array_unique($users);
print_r($uniqueUsers);
?>
How it works: The array_unique() function in PHP is used to remove duplicate values from an array. It takes an array as input and returns a new array where all duplicate entries have been removed. If multiple elements have the same value, the key of the first occurring element will be preserved. This function is particularly useful for cleaning up lists or sets of data.

Need help integrating this into your project?

Our team of expert developers can help you build your custom application from scratch.

Hire DigitalCodeLabs