PHP

Code Snippet to Find the Number of a Certain Value in an Array (PHP)

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 ( [1] => 3 [2] => 1 [3] => 1 [4] => 5 [5] => 1 [6] => 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:

5

2

And there we have it, now you can plug those variables in any where you’d like! Feel free to ask any questions below!

A web and application developer, based in Chicago, IL. Founder of Dragon Fruit Development (www.dragonfruitdevelopment.com) More articles by Todd Dunham
Home CSS Deals HTML HTML5 Java JavaScript jQuery Miscellaneous Mobile MySQL News PHP Resources Security Snippet Tools Tutorial Web Development Web Services WordPress