0

I am trying to find the Mode Average within an array of numbers, which works fine when the array only contains positive values. However, it seems to ignore any negative values in the array and I can't work out why?

$test_array = array(3.32,4,-5.51,2,4.44,1,2,3,5,-5.51,-5.51);

$v = array_count_values($test_array); 
arsort($v); 
foreach($v as $k => $v){$mode_avg = $k; break;} 

echo $mode_avg; 

This outputs "2", when it should output "-5.51" ?

James Parry
  • 61
  • 10
  • `break` ???????? – RiggsFolly Mar 20 '18 at 10:13
  • 2
    Turn on PHP warnings, and you'll see a lot of this: `Warning: array_count_values(): Can only count STRING and INTEGER values!` – iainn Mar 20 '18 at 10:14
  • `3.32` is a `float` not a `integer`, map the elements to `string`. – Aniket Sahrawat Mar 20 '18 at 10:18
  • Does that mean that I need to convert the array to a list of string values, then convert it back to a number after (for additional math processes) @iainn? Ignore the "break;" the code is part of a larger function that uses switch and i missed taking that out @RiggsFolly (well spotted) – James Parry Mar 20 '18 at 10:20
  • Oh....mod averge. Yeah my bad. Didn't read the question properly. – Andrei Mar 20 '18 at 10:22
  • I converted the string: //convert to string $test_array = array_map('strval', $test_array); and then converted it back using: //convert back to float $float = floatval($mode_avg); Is that the best solution @RiggsFolly ? – James Parry Mar 20 '18 at 10:39
  • 1
    @JamesParry Converting the array to a string and then the result back to a float makes sense to me as a workaround. Ultimately the limitation is that PHP arrays can't use floats as keys, so you'd otherwise need to come up with another data structure if you wanted to do it yourself. – iainn Mar 20 '18 at 10:58

1 Answers1

0

The mode of a numerical set is the number that occurs the most often. You can do this with PHP using code similar to the following:

$values = array_count_values($valueArray); 
$mode = array_search(max($values), $values);

Source

  • 1
    Did you miss this `Warning: array_count_values(): Can only count STRING and INTEGER values` – RiggsFolly Mar 20 '18 at 10:21
  • Yup. Could this still not work if all the numbers are multiplied by 100, calculated and divide the end result by 100? –  Mar 20 '18 at 10:23