Search code examples
phparrayslaravelcountlogic

Count How Many Times a Value Appears Php


i have a foreach and the code below returns to me the values (int) that you can see from Screenshot 1

foreach ($getMatches->participants as $data) {

  $count = ($data->id);
  

  echo '<pre id="json">'; var_dump($count); echo '</pre>';
   
  }

Screen shot 1

So, i want to count how many times the same value appears. In this case : Value 98 : 2 times ; Value 120: 3 times , etc.

I've tried to convert my $count variable to an array and use array_count_values like the code below , but with no success. As you can see in screenshot 2 the value 98 is returning only 1 instead of 2, the value 120 is returning only 1 instead of 3 , etc

  foreach ($getMatches->participants as $data) {

  $count = array($data->id);
  

  echo '<pre id="json">'; var_dump(array_count_values($count)); echo '</pre>';
   
  } 

Screen shot 2


Solution

  • array_count_values, enjoy :-)

    $array = array(12,43,66,21,56,43,43,78,78,100,43,43,43,21);
    //basically we get the same array
    foreach ($array as $data) {
    
      $count[] = $data;
    }   
    $vals = array_count_values($count);
    print_r($vals);
    

    Result:

    Array
    (
        [12] => 1
        [43] => 6
        [66] => 1
        [21] => 2
        [56] => 1
        [78] => 2
        [100] => 1
    )