0

Hi All,

Im trying to count the number of instances of a value in an array and put that value into a variable but im a little stuck.

My example below prints to screen how many of each, but i want it broken down to a specific variable of that count.

$values = array(1,1,1,1,2);
   $stateFrequency = array_count_values($values=1);
   print_r($stateFrequency);
3
Contributors
2
Replies
5
Views
6 Years
Discussion Span
Last Post by mschroeder
0
<?php
 $values = array(1,1,1,1,2);
   $i=0;
   $x=1;
   while(isset($values[$i]))
   {
     if($values[$i] == 1)  //you could use a strcmp or regex here instead
     {
         $number_of_matches = '$count'."$x";
         $number = $values[$i];
         echo "$number_of_matches = $number <br>";
         $x++;
     }
     $i++;
   }
?>
0

I'm not sure if I completely follow what you're asking but array_count_values will return a count of all unique values in your array. Returning an array of unique array items and their count.

First, you need to change $stateFrequency = array_count_values($values=1); to $stateFrequency = array_count_values($values); For your example array this would return:

Array
(
    [1] => 4
    [2] => 1
)

So if you want to know how many times 1 shows up in your array you can simply access it at $stateFrequency[1].

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.