Write a PHP program to count how many times a specific character appears in a given string

Counting how many times a specific character appears in a given string is a common string manipulation task in PHP. This program helps beginners understand how to work with strings, loops, conditional statements, and counters.

PHP Program: Count Character Occurrences in a String
Program:

<?php

$str = "programming";
$char = "m";
$count = 0;

for ($i = 0; $i < strlen($str); $i++) {
   if ($str[$i] == $char) {
       $count++;
   }
}

echo "Character: " . $char . "<br>";
echo "Total Occurrences: " . $count;

?>

Output:

Character: m
Total Occurrences: 2

Explanation

In this program, we first declare a variable named $str and assign the string "programming" to it. Next, we declare another variable named $char and assign the character "m", which we want to search for in the given string. We also initialize a variable $count with a value of zero.

After that, we use a for loop to iterate through each character of the string. The strlen() function returns the total length of the string, which determines how many times the loop will execute.

Inside the loop, we use an if condition to compare each character with the specified character stored in $char. Whenever a matching character is found, the $count variable is increased by one using the increment operator (++).

Finally, we use the echo statement to display the specified character and its total number of occurrences.

Since the character "m" appears two times in "programming", the final output is 2. This program works in PHP 7.4 and PHP 8.x.

10 Views