0

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' ) );
7
  • 1
    Why would you use array_sum()? They're not numbers, you can't add them. Commented May 4, 2021 at 20:35
  • I thought it maybe counts the occurrences but I was wrong. Commented May 4, 2021 at 20:36
  • And even if they were numbers, how would that tell you if there are duplicates? Commented May 4, 2021 at 20:36
  • 2
    You're thinking of array_count_values() Commented May 4, 2021 at 20:36
  • 1
    @miken32 I don't think that's right, either. This is looking in a specific key of associative arrays. Commented May 4, 2021 at 20:41

1 Answer 1

2

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; }));
Sign up to request clarification or add additional context in comments.

5 Comments

Awesome! That's what I was looking for! Thanks Barmar :)
I'm not sure what the benefit of declaring it static is.
Thats just how I learned it so I thought it might be correct. I think this is just a style decision.
From the documentation: Anonymous functions may be declared statically. This prevents them from having the current class automatically bound to them. Unless the code is inside a class, it doesn't make any difference.
Thanks for the explanation. Now it makes sense.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.