I recently developed an application that sent variables into a mathematic function. This function needed to have a numeric count of the exactly how many zeros there were in a certain array. For this snippet, we can use both numeric and text based arrays.
I printed it using this code:
Our two example arrays will be:
$array_num = array(1, 1, 1, 2, 3, 4, 4, 4, 4, 4, 5, 6); $array_text = array(apple, apple, apple, orange, banana, banana);
We then put this array into array_count_values()
$count_array_num = array_count_values($array_num); $count_array_text = array_count_values($array_text);
If we print $count_array_num we get this result:
Array (  => 3  => 1  => 1  => 5  => 1  => 1 )
if we print $count_array_text we get:
Array ( [apple] => 3 [orange] => 1 [banana] => 2 )
From these results, we see the exact number of each value in the respective array.
Then we can define the values that we want to know:
$value_num = '4'; $value_text = "banana";
Finally, we can use this code to get the count for how many times the number 4 shows up in our $array_num and how many times ‘banana’ is listed in $array_text.
$result_num = $count_array_num[$value_num]; $result_text = $count_array_text[$value_text];
And of course, echo the results!
echo $result_num; echo '<br/>'; echo $result_text;
Now our page result will be:
And there we have it, now you can plug those variables in any where you’d like! Feel free to ask any questions below!