Lucas Ln
Lucas Ln

Reputation: 77

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

Upvotes: 1

Views: 1427

Answers (4)

ctoma91
ctoma91

Reputation: 9

array_count_values does exactly what you need, there is no need for another loop.

$array = [25,943,943,21,9,25,943,1,2,4];
$counts = array_count_values($array);

Result is:

[
   25 => 2,
   943 => 3,
   21 => 1,
   9 => 1,
   1 => 1,
   2 => 1,
   4 => 1,
]

Upvotes: -1

Donkarnash
Donkarnash

Reputation: 12835

You are not getting the desired results probably as you are doing everything within the foreach loop

Let's try with Laravel collections

$items = collect([]);

foreach ($getMatches->participants as $data) {
    $items->push($data->id);   
}

dd($items->countBy()->all());

Upvotes: 1

Lessmore
Lessmore

Reputation: 1091

If $getMatches->participants is an array of objects, you should to first iterate a loop over that and sum of repeats.

$count = [];
foreach ($getMatches->participants as $data)
{
    if (isset($count[$data->id]))
    {
        $count[$data->id] = $count[$data->id] + 1;
    }
    else
    {
        $count[$data->id] = 1;
    }
}

Then in other loop show the result

echo '<pre id="json">';
foreach ($count as $key => $data)
{
    echo $key . ' repeated ' . $data . ' times'. PHP_EOL;
}
echo '</pre>';

Upvotes: 0

Serghei Leonenco
Serghei Leonenco

Reputation: 3507

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
)

Upvotes: 2

Related Questions