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
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.