Current Location: Home> Latest Articles> Use array_count_values() to process string arrays

Use array_count_values() to process string arrays

M66 2025-06-07

In PHP, the array_count_values() function is used to count the number of occurrences of each value in an array. It returns an associative array where the key is the element in the array and the value is the number of times the element appears in the array. This is very useful for scenarios where you need to know how many times some elements are repeated in an array.

This article will demonstrate how to use array_count_values() to count the number of occurrences of each element in a string array.

Sample code

 <?php
// Define an array of strings
$array = array("apple", "banana", "apple", "orange", "banana", "apple");

// use array_count_values Count the number of occurrences of each element
$count_values = array_count_values($array);

// Output statistics
print_r($count_values);
?>

Code parsing

  1. Define string array <br> In the above code, we first define a string array containing the fruit name $array . Some elements in the array (such as "apple" and "banana") appear several times.

  2. Call array_count_values()
    Using the array_count_values($array) function, we can count the number of occurrences of each element in $array and save the result in the $count_values ​​variable.

  3. Output statistics results <br> Finally, use print_r($count_values) to output the result to the browser. The output will be an associative array where the key is the string in the array and the value is the number of times the string appears.

Output result

 Array
(
    [apple] => 3
    [banana] => 2
    [orange] => 1
)

As shown above, the output results show:

  • "apple" appears 3 times.

  • "banana" appears 2 times,

  • "orange" appears 1 time.

Use scenarios

  • Analyze log data
    array_count_values() can be used to count the occurrence of various events in certain log files, helping to analyze the most frequent events.

  • Processing user data <br> In some user input data, counting the occurrence of a specific value can help identify hot content or common errors.

  • Word frequency analysis <br> In text processing, array_count_values() can be used to calculate the frequency of occurrence of each word in the text.

Things to note

  • array_count_values() only counts the value and does not care about the type of the value. If the array contains the same values ​​of different types (such as the string "1" and the integer 1), they will be treated as different elements.

  • If the array is empty, array_count_values() returns an empty array.

URL replacement

In actual development, we may include URLs in array elements. If you need to replace the URL domain name with m66.net , you can use the str_replace() function to replace the string. Here is a simple example: