0
Follow
2
View

Using array_count_values in foreach loop

gala42 注册会员
2023-01-25 01:45

Loop over the result of the a array_count_values() and its easy.

$number='9,9,4,4,22,22,22';
$result = explode(',',$number);
print_r(array_count_values($result));

foreach(array_count_values($result) as $n=>$occ) {
    echo "$n = $occ occurrences 
" . PHP_EOL; }

RESULT

The array_count_value() produces an array with the key being the numbers being counted and the value as the occurances of the numbers

Array
(
    [9] => 2
    [4] => 2
    [22] => 3
)

So the output is

9 = 2 occurrences 
4 = 2 occurrences
22 = 3 occurrences
cs79715964cs 注册会员
2023-01-25 01:45

You will need to handle the user input then before going inside your loop.

$result = explode(',',$number);
foreach (array_unique($result) as $value){
   echo "$value = ".array_count_values($result) 
   [$value]." occurrences 
"; }

You will keep only the unique values in your array so you will loop only once per value.

dmgz88 注册会员
2023-01-25 01:45

array_count_values function provides the unique elements in an array as the keys and also provides the number of occurrences as the values in the array. So the solution can be as mentioned below:

 $value) {
        echo "{$key} = {$value} occurrences 
"; } ?>

About the Author

Question Info

Publish Time
2023-01-25 01:45
Update Time
2023-01-25 01:45