PHP: Count-IF for arrays

What would be the most efficient way to count the number of times a value appears inside an array?

Array example ('apple', 'apple', 'banana', 'banana', 'kiwi')

Ultimately, I want the function to spit out interest for charting purposes (e.g. apple = 40%, banana = 40%, kiwi = 20%)

+4
source share
3 answers

Just enter array_count_values . Interest should be light ...

 $countedArray = array_count_values($array); $total = count($countedArray); foreach ($countedArray as &$number) { $number = ($number * 100 / $total) . '%'; } 
+3
source

Use array_count_values() :

 <?php $array = array(1, "hello", 1, "world", "hello"); print_r(array_count_values($array)); ?> 

The above example outputs:

 Array ( [1] => 2 [hello] => 2 [world] => 1 ) 
+2
source
 $a = Array ('apple','apple','banana','banana','kiwi'); $b = array_count_values($a); function get_percentage($b,$a){ $a_count = count($a); foreach ($b as $k => $v){ $ret[$k] = $v/$a_count*100."%"; } return $ret; } $c = get_percentage($b,$a); print_r($c); 
0
source

Source: https://habr.com/ru/post/1303900/


All Articles