0

If I have: $mainarray = some array of things with some repeated values

$array_counted = array_count_values ($mainarray);

How can I find the maximum value in $array_counted?

(This would be the element that appeared most often in $mainarray I think. Its mostly a syntax issue as I am pretty sure I could loop it, but not sure of the syntax to use)

4 Answers 4

1

You can find first max value as

$main_array = array(1,2,3,4,5,6,6,6,6,6,6,6);
$max_val = max($main_array);

for find all of max vals in php < 5.3

  function findmax($val)
{
    global $max_val;
    return $val == $max_val;
}
$max_values_array = array_filter($main_array,'findmax');

in php >= 5.3

 $max_values_array = array_filter($main_array,function($val) use  ($max_val)  {  return $val == $max_val; }); 

echo count($max_values_array); 

var_dump($max_values_array);

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

Comments

0

You could sort the array and take the first, respectively last item out of it, if you don't want to loop.

Comments

0

Since you associate the count with the values with that:

$array_counted = array_count_values ($mainarray);

You only need to sort it afterwards, and return the first key (which is the most occured element):

arsort($array_counted);
print key($array_counted);  // returns first key

Comments

0

ok, the guy whos answer I used has deleted his comment so here is how I did it:

I used arsort($array_counted) to sort the array, while keeping index. rsort alone does not work as the result of array_count_values is an associative array. Thank you all.

Comments

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.