PHP provides useful functions to manipulate array values. The array_values() and array_unique() functions are commonly used to work with arrays that may have duplicate values or non-sequential keys. These functions help you clean up and retrieve unique values from arrays.
array_values() – Returns all the values from an array and reindexes the array numerically.array_unique() – Removes duplicate values from an array and returns a new array with only unique values.array_values() is useful when you need a clean indexed array, while array_unique() focuses on removing repeated values. Both functions return new arrays and do not modify the original array.
// Reindexing an associative array into a numeric array
<?php
$array = array("a" => "apple", "b" => "banana", "c" => "cherry");
$values = array_values($array);
print_r($values);
?>
The array_values() function extracts only the values and resets the keys starting from index 0.
// Removing duplicate values from an indexed array
<?php
$array = array("apple", "banana", "apple", "cherry", "banana");
$unique = array_unique($array);
print_r($unique);
?>
The duplicate values are removed while the original keys remain unchanged.
// Removing duplicate values while preserving associative keys
<?php
$array = array("a" => "apple", "b" => "banana", "c" => "apple", "d" => "cherry");
$unique = array_unique($array);
print_r($unique);
?>
Only duplicate values are removed, and the first occurrence of each value keeps its original key.
array_values()
array_unique()
Try switching themes using the toggle above to see how code readability adapts to light and dark modes.
array_values() after array_unique() if you need sequential indexes.array_unique() compares values only, not keys.