0

I have an array which contain multiple values inside it, all i want is to find duplicate items and add the number of times they are inside an array. Here goes an example

$someVar = array('John','Nina','Andy','John','Aaron','John','Zack','Kate','Nina');

I want my final result to look like

John = 3;
Nina = 2;

and so on.

EDIT | These values are dynamic i have no idea what these names going to be.

Thanks

3

1 Answer 1

4

Use array_count_values() and array_filter() to achieve this.

$result = array_filter( array_count_values( $someVar), function( $el) {
    return $el > 1; 
});

$result will be an associative array containing the names as keys and the number of times they occur as values, but only if they were duplicated in the $someVar array.

Here is a demo showing the correct output.

Sign up to request clarification or add additional context in comments.

2 Comments

just checked the demo , it's exactly what i want... thanks a lot
if have used $el >= 1, so that i can also get those which are only for one time...

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.