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:
To remove duplicate values from a multi-dimensional array in PHP, you can use the following approach:
- Flatten the multi-dimensional array into a single-dimensional array using the
array_merge()function. - Remove duplicate scalar values using the
array_unique()function. - Reshape the array back into a multi-dimensional structure using the
array_chunk()function. Note: This method assumes all original sub-arrays had identical lengths. If the deduplicated count is not divisible by that length, the final sub-array will be shorter.
Here is an example of how you can implement this:
How to remove duplicate values from a multi-dimensional array in PHP?
<?php
$input = [[1, 2, 3], [2, 3, 4], [3, 4, 5]];
// Flatten the multi-dimensional array into a single-dimensional array
$single_dimensional_array = array_merge(...$input);
// Remove duplicate scalar values
$single_dimensional_array = array_unique($single_dimensional_array);
// Reshape back into a multi-dimensional array
// Note: Assumes fixed sub-array lengths. The last chunk may be shorter if the count isn't divisible.
$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, reshaped to match the original sub-array length.