I took @alistaircol Idea and not only fixed it (as it's dependent on the order of the array) but I also simplfied the assignment part so we are not creating 2 new arrays
You can try it here
http://sandbox.onlinephpfunctions.com/code/2fe11fb6040dc68db43fb5cbb858ef3e47394dd2
And here is the code
$items = [370,370,546,55,55,55];
$counted = array_count_values($items);
arsort($counted); //sort descending maintain keys
$occurences = reset($counted); //get the first value (rewinds internal pointer )
$most_frequent = key($counted); //get the key, as we are rewound it's the first key
echo $most_frequent . ' appears ' . $occurences . ' time(s)' . PHP_EOL;
This correctly outputs
55 appears 3 time(s)
Just FYI @alistaircol original answer would fail this test case
http://sandbox.onlinephpfunctions.com/code/fe13e7a0bd00ea1219bc69e2bc5a5aebaf478034
Which is changing the input array from:
$items = [370,370,546,55];
To:
$items = [370,370,546,55,55,55];
It would still output:
370 appears 2 time(s)
In this case when the correct answer is 55 appears 3 time(s)
This way the item with the most is the last one, which exposes that it's based on the order ( which was obvious to me because of using the first index [0]
)
Not to call him out on it, but as it was accepted as the answer I felt I should point that out. Overall though I was a sound approach to the question. So Kudos on that.
UPDATE
One way to get all values that show more then one time is like this:
$items = [370,370,546,55,55,55];
$unique = array_unique( $items );
$diff = array_diff_assoc( $items, $unique);
print_r( $diff );
Which outputs
Array
(
[1] => 370
[4] => 55
[5] => 55
)
You can test it here http://sandbox.onlinephpfunctions.com/code/53df6a8ea7a68768572cfef494e3b715aa13e83b
One note, is that you will get exactly one less occurrence then is actually present.
UPDATE1
We can easily combine these and account for the missing one. See this fiddle to test that
http://sandbox.onlinephpfunctions.com/code/1bc1a30a5e091af3a18fec2c8b48050869108549
And the code:
$items = [370,370,546,55,55,55];
$unique = array_unique( $items );
$diff = array_diff_assoc( $items, $unique);
print_r( $diff );
echo "\n\n";
$counted = array_count_values($diff);
arsort($counted); //sort descending maintain keys
$occurences = reset($counted); //get the first value (rewinds internal pointer )
$most_frequent = key($counted); //get the key, as we are rewound it's the first key
echo $most_frequent . ' appears ' . ( $occurences + 1 ) . ' time(s)' . PHP_EOL;
Outputs ( both the previous ones )
Array
(
[1] => 370
[4] => 55
[5] => 55
)
55 appears 3 time(s)
Oh and if you want the ones that are more then one as a list with no duplicates, then just hit it again with array unique $unique = array_unique($diff);
Cheers!
max()
returns the highest value, it doesn't care how many times this value occurs in the array.546
is the highest value from$item
and2
is its index (position) in the array. It is not a count.