To remove duplicate values from an array in PHP, you can use the array_unique
function. This function removes duplicate values from an array and returns a new array with only unique values.
Here’s an example:
$array = [1, 2, 3, 1, 2, 3, 4, 5];
$unique = array_unique($array);
// $unique is now [1, 2, 3, 4, 5]
You can also use the array_values
function to re-index the array after removing the duplicates:
$array = [1, 2, 3, 1, 2, 3, 4, 5];
$unique = array_values(array_unique($array));
// $unique is now [1, 2, 3, 4, 5] with sequential keys starting from 0
If you want to preserve the keys of the original array, you can use the array_keys
function to get an array of the keys, and then use the array_combine
function to create a new array with the unique keys and values:
$array = [
'a' => 1,
'b' => 2,
'c' => 3,
'd' => 1,
'e' => 2,
'f' => 3,
'g' => 4,
'h' => 5,
];
$keys = array_keys($array);
$values = array_unique($array);
$unique = array_combine($keys, $values);
// $unique is now ['a' => 1, 'b' => 2, 'c' => 3, 'g' => 4, 'h' => 5]