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);
<?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++;
   }
?>

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].

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.