thecodedeveloper.com
thecodedeveloper.com

Reputation: 3240

Find only duplicate values in associative array in php

This is my array output -

print_r($array_email);

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

    [2] => Array
        (
            [0] => [email protected]
        )

    [3] => Array
        (
            [0] => [email protected]
        )

    [4] => Array
        (
            [0] => [email protected]
        )

)

Here i have tried - (but not working)

function get_duplicates( $array ) {
                return array_unique( array_diff_assoc( $array, array_unique( $array ) ) );
            }

print_r(get_duplicates($array_email));

I need output like that-

Array
    (
        [1] => Array
            (
                [1] => [email protected]
                [2] => [email protected]
                [4] => [email protected]
            )

        [2] => Array
            (
                [0] => [email protected]
            )
        [4] => Array
            (
                [0] => [email protected]
            )

    )

Upvotes: 0

Views: 838

Answers (2)

Alexander Guz
Alexander Guz

Reputation: 1364

You have to do this:

array_walk($arr, function(&$value) {
    $value = array_unique($value);
});

$arr = array_unique($arr, SORT_REGULAR);

array_walk will remove duplicates inside inner arrays. array_unique will do the rest.

Upvotes: 0

Aleksei Matiushkin
Aleksei Matiushkin

Reputation: 121000

If I understood your requirement correctly:

array_map(function($elem) {
    return array_unique($elem);
});

Upvotes: 3

Related Questions