w3resource

PHP Array Exercises : Count the total number of times a specific value appears in an array


37. Count Occurrences of a Specific Value in Array

Write a PHP script to count the total number of times a specific value appears in an array.

Sample Solution:

PHP Code:

<?php
// Define a function to count occurrences of a value in an array
function count_array_values($my_array, $match) 
{ 
    $count = 0; 
    
    // Iterate through each element in the array
    foreach ($my_array as $key => $value) 
    { 
        // Check if the current element matches the specified value
        if ($value == $match) 
        { 
            // Increment the count if a match is found
            $count++; 
        } 
    } 
    
    // Return the total count of occurrences
    return $count; 
} 

// Define an associative array with color values
$colors = array("c1"=>"Red", "c2"=>"Green", "c3"=>"Yellow", "c4"=>"Red");

// Display the count of occurrences of the value "Red" in the array
echo "\n"."Red color appears ".count_array_values($colors, "Red"). " time(s)."."\n"; 

?>

Output:

Red color appears 2 time(s).

Flowchart:

Flowchart: PHP - Count the total number of times a specific value appears in an array

For more Practice: Solve these Related Problems:

  • Write a PHP script to count how many times a given value appears in an array without using array_count_values().
  • Write a PHP function to iterate over an array and increment a counter each time a specific value is encountered.
  • Write a PHP program to filter an array for a given target and then return the count of the matching values.
  • Write a PHP script to implement a manual counter for array elements and output the frequency of a specified integer.

Go to:


PREV : Convert Array Elements to Lower and Upper Case.
NEXT : Multidimensional Unique Array by Key Index.

PHP Code Editor:



Contribute your code and comments through Disqus.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Follow us on Facebook and Twitter for latest update.