Soulsmasher
Soulsmasher

Reputation: 23

Remove duplicates from array comparing a specific key

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 ) );

Upvotes: 1

Views: 39

Answers (2)

jspit
jspit

Reputation: 7683

Without foreach with array_column.

$array = array_column($all_array,null,'value');
$array = array_values($array);  //if the array is to be re-indexed

var_dump($array);

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

Upvotes: 1

Death-is-the-real-truth
Death-is-the-real-truth

Reputation: 72299

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

Upvotes: 0

Related Questions