Alex Polly Alex Polly - 3 months ago 9
PHP Question

Make array value unique

this is the dynamic array. I'm trying to remove the repeated value and have only merged one. e.g. need to remove

[0] => 1/2/48 & [1] => 1/2/48/56
and only have
[2] => 1/2/48/56/58
.

Array(
[0] => 1/2/48
[1] => 1/2/48/56
[2] => 1/2/48/56/58
[3] => 1/2/245
[4] => 1/2/245/246
[5] => 1/2/265
)


So the array should look like

Array(
[0] => 1/2/48/56/58
[1] => 1/2/245/246
[2] => 1/2/265
)

Answer

One way to do it

$a = [
    '1/2/48',
    '1/2/48/56',
    '1/2/48/56/58',
    '1/2/245',
    '1/2/245/246',
    '1/2/265'
];

$result = array_values(
    array_filter($a, function ($value, $index) use ($a) {
        return !isset($a[$index + 1]) || 
               strpos($a[$index + 1], $value) !== 0;
    }, ARRAY_FILTER_USE_BOTH)
);

This assumes that your input array $a is sorted as you showed. Otherwise you'd need to sort it first.