Skip to content
Advertisement

PHP check if value in array of objects exists more than once

I’ve this array here with multiple object:

$batches = [
    [
        'id' => 2,
        'number' => 'ABC'
    ],
    [
        'id' => 3,
        'number' => 'ABC'
    ],
    [
        'id' => 4,
        'number' => 'DEF'
    ]
];

Now I need to know if there are any numbers that exists more than once. In this case its ABC.

I’ve tried using array_sum and array_column but this seems to only work with numbers:

$test = array_sum( array_column( $batches, 'number' ) );

Advertisement

Answer

Use array_count_values() to count the repetitions. Then you can filter this to just the ones with counts more than 1.

$results = array_keys(
    array_filter(array_count_values(array_column($batches, 'number')),
                 static function($count) { return $count > 1; }));
User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement