Nerd Talk
array_count_values function in PHP can only count integer and string values. At some point you may need to count occurrences of float values in an array but you can’t because array_count_values won’t let you. If you have an array like:
$digits = array(14.5, 5.42, 1.5, 8, 14.5); $digits = array_count_values($digits);
This will give you a warning that says, Warning: array_count_values() [function.array-count-values]: Can only count STRING and INTEGER values!
There’s actually a hack to get around this and achieve counting occurrences of float values. All you need to do is cast all float values in the array as string. array_count_values can also count integers so why not just cast the values as int? You don’t want to do that because casting the float values as int will change the data type to int but also remove the decimal points in your values and make it a whole number. Take this as an example:
$float = 12.8; var_dump($float); // float(12.8) - original float value var_dump((int)$float); // int(12) - becomes whole number var_dump(intval($float)); // int(12) - becomes whole number var_dump((string)$float); // string(4) "12.8" - string type
Based on the example above we need to cast the float values as string. So in the case of the array that we want to count the values, we need to do something like:
$digits = array(14.5, 5.42, 1.5, 8, 14.5); $newDigits = array(); foreach($digits as $key => $value) // cast float as string if(is_float($value)) $newDigits[$key] = (string)$value; // for actual int and string values else $newDigits[$key] = $value; $countValues = array_count_values($newDigits); print_r($countValues);
The above code will cast all float values in the array as string and array_count_values will work as expected. The output will be:
Array ( [14.5] => 2 [5.42] => 1 [1.5] => 1 [8] => 1 )
Hope that helps!