count number of value per id in array

Viewed 125

I have this script in php i want to get the number of value in the table in below my script

$count = 0;
         
foreach ($info as $key => $value)
{
    foreach ($value as $c => $val)
    {
        var_dump($val) . "<br>";
                 
        if (strcmp($val,"Tankh ") == 0)
        {
            $count++;
            //echo $count;
        }
    }

    // die();
                      
    echo $count;
    return $count;

var_dump the $val:

string(9) "Nomclient" 
string(13) "Villeclient " 
string(7) "Mohamed" 
string(8) "Tankh " 
string(6) "Fatima" 
string(9) "Tankh " 
string(6) "Brahim" 
string(6) "Tankh " 
string(5) "Jamal" 
string(8) "Tankh " 
string(5) "Ikram" 
string(6) "Tankh " 
string(6) "Karima" 
string(5) "Rain"

thanks in advance

2 Answers

I think you'd want something like this... if I understand correctly:

$val_counts = array();

foreach ($info as $key => $value)
{
   foreach ($value as $c => $val)
   {
      $val_counts[$val]++;
   }
}

Then later, var_dump($val_counts) and you'll see how many time each value was in your 2-dimensional array.

Perhaps you can leverage the existing function array_count_values for every $value instead of checking the individual values.

$info = [
    [
        "Nomclient", "Villeclient", "Mohamed", "Tankh", "Fatima", "Tankh", "Brahim", "Tankh", "Jamal", "Tankh", "Ikram", "Tankh", "Karima", "Rain"
    ]
];

$val_counts = array_map(function($value){
    return array_count_values($value);
}, $info);

print_r($val_counts);

Output

Array
(
    [0] => Array
        (
            [Nomclient] => 1
            [Villeclient] => 1
            [Mohamed] => 1
            [Tankh] => 5
            [Fatima] => 1
            [Brahim] => 1
            [Jamal] => 1
            [Ikram] => 1
            [Karima] => 1
            [Rain] => 1
        )

)

PHP demo

Related