PHP

Get All Unique Values from an Array

Discover how to efficiently remove duplicate values from a PHP array, ensuring each element is unique, and retaining the first encountered key association.

<?php
$data = ['apple', 'banana', 'orange', 'apple', 'grape', 'banana'];

$uniqueValues = array_unique($data);
print_r($uniqueValues);

$associativeData = [
    'a' => 'red',
    'b' => 'blue',
    'c' => 'red',
    'd' => 'green',
    'e' => 'blue'
];

$uniqueAssociativeValues = array_unique($associativeData);
print_r($uniqueAssociativeValues);
How it works: The `array_unique()` function is used here to remove duplicate values from an array. When applied, it returns a new array where each value appears only once. For associative arrays, it preserves the key of the first occurrence of each value. This function is essential for data cleaning and ensuring uniqueness in lists of items.

Need help integrating this into your project?

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

Hire DigitalCodeLabs