Current Location: Home> Latest Articles> Comprehensive Guide to Counting Character Occurrences in PHP Strings with Practical Code Examples

Comprehensive Guide to Counting Character Occurrences in PHP Strings with Practical Code Examples

gitbox 2025-07-26

Introduction

PHP (Hypertext Preprocessor) is a widely used open-source scripting language commonly embedded within HTML. It offers low learning curve, flexibility, and efficiency. String handling is a frequent task in PHP development, with counting character occurrences being a common requirement.

Methods to Count Character Occurrences

Traditional Method

Counting characters by iterating over each character in the string and using an array to tally counts is a classic approach. The following example demonstrates how to use a for loop with if statements to accomplish this:


$str = "hello world";

$count_array = array();
for ($i = 0; $i < strlen($str); $i++) {
    $char = $str[$i];
    if (isset($count_array[$char])) {
        $count_array[$char]++;
    } else {
        $count_array[$char] = 1;
    }
}

foreach ($count_array as $char => $count) {
    echo "$char: $count \n";
}

This code uses an array to store counts for each character. It checks if the character already exists as a key in the array; if so, it increments the count, otherwise initializes it to 1. Finally, it outputs the counts for all characters.

Using PHP Built-in Functions

Besides the traditional method, PHP offers two useful built-in functions, count_chars() and substr_count(), which simplify counting character occurrences.

count_chars()

The count_chars() function returns the frequency of each character in a string, with ASCII values as keys and their counts as values. Here is an example:


$str = "hello world";

$result = count_chars($str, 1);

foreach ($result as $char => $count) {
    echo chr($char) . ": $count \n";
}

The parameter '1' specifies returning all characters that appear in the string along with their counts. The chr() function converts ASCII values back to characters for display.

substr_count()

The substr_count() function counts the number of times a specified substring occurs within a string. It is suitable for counting a specific character or substring. Example:


$str = "hello world";

$count = substr_count($str, "l");
echo "'l' appears $count times";

This function returns the count of the target character "l" in the string directly, making it simple and efficient.

Conclusion

This article introduced various ways to count character occurrences in PHP strings. The traditional loop method helps beginners understand the underlying mechanics, while PHP's built-in functions count_chars() and substr_count() offer concise and maintainable code. Choose the method that best fits your needs for efficient string processing.