Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP How to count same words in foreach loop

I have this result inside my foreach loop:

Tonsilitis
Tonsilitis
Laryngitis
Rhinosinusitis Akut
Rhinosinusitis Akut
Rhinosinusitis Akut
Common Cold
Common Cold
Common Cold
Rhinitis Alergi

This is my script:

foreach ($results as $data) :
   $final = $data->nama_diagnosis . '<br>';
   echo $final;
endforeach;

My question is, how can i count the same word in my loop or outside the loop. Can i do that? give me the solution please. As a result i want to count them like this:

Tonsilitis = 2
Laryngitis = 1
Rhinosinusitis Akut = 3
Common Cold = 3
Rhinitis Alergi = 1

Or maybe i can filter the same word so i get only the most words, like Rhinosinusitis Akut and Common Cold. Please help me. Thanks

like image 513
RK26 Avatar asked Feb 22 '26 19:02

RK26


2 Answers

You can try something like this, iterating through array with foreach loop and using a ternary operator with isset to safely assign and increment each occurrence:

$count = array();
foreach ($results as $result)
    isset($count[$data]) ? $count[$data]++ : $count[$data] = 1;

Example

like image 156
potashin Avatar answered Feb 25 '26 09:02

potashin


In foreach loop save words and their count into array, then make another loop and write the amounts.

<?php

$results = array(
    array('nama_diagnosis' => 'Tonsilitis'),
    array('nama_diagnosis' => 'Tonsilitis'),
    array('nama_diagnosis' => 'Laryngitis'),
    array('nama_diagnosis' => 'Rhinosinusitis Akut'),
    array('nama_diagnosis' => 'Rhinosinusitis Akut'),
    array('nama_diagnosis' => 'Rhinosinusitis Akut'),
    array('nama_diagnosis' => 'Common Cold'),
    array('nama_diagnosis' => 'Common Cold'),
    array('nama_diagnosis' => 'Common Cold'),
    array('nama_diagnosis' => 'Rhinitis Alergi')
);

$res = array();
foreach ($results as $words) {  // changed $word to $words
    foreach ($words as $word) { // this foreach added
        if (isset($res[$word])) {
            $res[$word] += 1;
        } else {
            $res[$word] = 1;
        }
    } // end of nested foreach which was added
}

foreach ($res as $word => $count) {
    echo $word . ' (' . $count . ')<br>';
}

/*
    output:

    Tonsilitis (2)
    Laryngitis (1)
    Rhinosinusitis Akut (3)
    Common Cold (3)
    Rhinitis Alergi (1)
*/

?>
like image 26
pavel Avatar answered Feb 25 '26 09:02

pavel



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!