Home > Enterprise >  Remove duplicates from array comparing a specific key
Remove duplicates from array comparing a specific key

Time:09-21

Consider the same array but id of 3rd index is different:

$all_array = Array
(
    [0] => Array
        (
            [id] => 1
            [value] => 111
        )

    [1] => Array
        (
            [id] => 2
            [value] => 222
        )

    [2] => Array
        (
            [id] => 3
            [value] => 333
        )

    [3] => Array
        (
            [id] => 4
            [value] => 111
        )
)

Now, both 1 & 4 have same values. So we want to remove any of them:

$unique_arr = array_unique( array_column( $all_array , 'value' ) );
print_r( array_intersect_key( $all_array, $unique_arr ) );

CodePudding user response:

You can use foreach() for it:

$finalArray = [];

foreach($all_array as $arr){
    
    $finalArray[$arr['value']] = $arr;
}

print_r($finalArray);
print_r(array_values($finalArray)); // to re-index array

https://3v4l.org/82XUI

Note: this code will give you always the last index data of the duplicate once

  • Related