How to remove duplicate values from a multi-dimensional array in PHP
To remove duplicate values from a multi-dimensional array in PHP, you can use the following approach:
- First, convert the multi-dimensional array into a single-dimensional array using
array_merge()
function. - Then use the
array_unique()
function to remove the duplicate values from the single-dimensional array. - Finally, convert the single-dimensional array back into a multi-dimensional array using
array_chunk()
function.
Here is an example of how you can implement this:
<?php
$input = [[1, 2, 3], [2, 3, 4], [3, 4, 5]];
// Convert the multi-dimensional array into a single-dimensional array
$single_dimensional_array = array_merge(...$input);
// Remove the duplicate values from the single-dimensional array
$single_dimensional_array = array_unique($single_dimensional_array);
// Convert the single-dimensional array back into a multi-dimensional array
$result = array_chunk($single_dimensional_array, count($input[0]));
print_r($result);
The resulting array $result
will contain the values of the original array $input
with duplicate values removed.