Home > OS >  How to remove duplicate values from array - php
How to remove duplicate values from array - php

Time:01-05

I am trying to remove duplicate and empty values from array with array_unique() function, but getting wrong output.

Data:

Array (
    [0] => Array  (
            [0] => 
            [1] => 1
            [2] => 
            [3] => 108
            [4] => 
        )
    [1] => Array (
            [0] => 
            [1] => 1
            [2] => 
            [3] => 108
            [4] => 
            [5] => 101
        )
    [2] => Array (
            [0] => 
            [1] => 
            [2] => 108
            [3] => 
        )
)

PHP:

$array = array_filter($userids);
$arrays = array_unique($array, SORT_REGULAR);
print_r($arrays);

nothing happens with SORT_REGULAR - output comes same as raw data, and without SORT_REGULAR this output is coming:

$array = array_filter($userids);
$arrays = array_unique($array);
print_r($arrays);

output:

Array (
    [0] => Array
        (
            [0] => 
            [1] => 1
            [2] => 
            [3] => 108
            [4] => 
        )
    )

output I am looking for:

Array (
    [0] => Array
        (
            [0] => 1
            [1] => 108
            [2] => 101 
        )
)

CodePudding user response:

Those array functions only works on a single level. If you flatten the array (adding all elements in a single element array), it should be pretty straight forward.

Flatten the array

$array = array_merge(...$array);

Note: This method works fine for flattening indexed arrays like in your example, but not for associative arrays where any of the sub arrays contains the same keys.

Then filter out all empty

$array = array_filter($array);

and then remove all duplicates

$array = array_unique($array);

Or as a one-liner:

$array = array_unique(array_filter(array_merge(...$array)));

Demo: https://3v4l.org/pEJAJ

CodePudding user response:

Another alternative:

foreach ($array as &$level1) {
    $level1 = array_unique($level1);
}

Edit:

I just realized that the question was different, in my answer only the duplicates of each key of the first level are removed, and not of the whole array globally.

CodePudding user response:

According to @M.Eriksson suggestion, I flatten the multidimensional array using: $array = array_merge(...$array); and got the desired output.

Thanks.

$array_ids = array_merge(...$userids);
print_r(array_filter(array_unique($array_ids)));
  •  Tags:  
  • php
  • Related