PHP
Remove Duplicate Values from a PHP Array
Efficiently remove duplicate elements from a PHP array, preserving the first occurrence and maintaining original keys if needed. Learn to use array_unique() for clean data processing.
<?php
$originalArray = [1, 2, 2, 3, 4, 4, 5];
$uniqueArray = array_unique($originalArray);
$associativeArray = ['a' => 1, 'b' => 2, 'c' => 2, 'd' => 3, 'e' => 4, 'f' => 4, 'g' => 5];
$uniqueAssociativeArray = array_unique($associativeArray);
echo "Original Numeric: ";
print_r($originalArray);
echo "Unique Numeric: ";
print_r($uniqueArray);
echo "Original Associative: ";
print_r($associativeArray);
echo "Unique Associative: ";
print_r($uniqueAssociativeArray);
?>
How it works: The array_unique() function removes duplicate values from an array. For arrays with duplicate values, only the first occurrence is kept. It works for both numerically indexed and associative arrays, maintaining the original keys in the resulting array. This is ideal for cleaning up datasets where each value should only appear once.