w3resource

PHP for loop Exercises: Count a specified characters in a string


7. Count "r" Characters in a String

Write a program which will count the "r" characters in the text "w3resource".

Visual Presentation:

PHP for loop Exercises: Count a specified characters in a string

Sample Salution:

PHP Code:

<?php
// Define the text string to search within
$text = "w3resource";

// Define the character to search for
$search_char = "r";

// Initialize a counter variable to count occurrences
$count = "0";

// Loop through each character in the text string
for($x = "0"; $x < strlen($text); $x++)
  { 
    // Check if the current character matches the search character
    if(substr($text, $x, 1) == $search_char)
    {
        // Increment the counter if there's a match
        $count = $count + 1;
    }
  }

// Print the count of occurrences of the search character
echo $count."\n";

?>

Output:

2

Explanation:

In the exercise above,

  • The code begins with a PHP opening tag <?php.
  • It initializes three variables:
  • $text: Contains the text string to search.
  • $search_char: Contains the character to count.
  • $count: Initializes a counter variable to count the occurrences of the search character.
  • The code enters a "for" loop to iterate over each character in the text string. The loop condition is based on the length of the text string (strlen($text)).
  • Within the loop, it uses "substr()" function to extract each character from the text string (substr($text, $x, 1)) and compares it with the search character ($search_char).
  • If the current character matches the search character, the counter ('$count') is incremented by 1.
  • After iterating through all the characters in the text string, the code prints out the count of occurrences of the search character using "echo".
  • Finally, PHP code ends with a closing tag ?>.

Flowchart:

Flowchart: Count a specified characters in a string

For more Practice: Solve these Related Problems:

  • Write a PHP script to count the occurrences of the letter "r" in any given string, ignoring case sensitivity.
  • Write a PHP function that takes a string as input and returns the frequency of a specified character (e.g., "r"), using a loop.
  • Write a PHP program to use substr_count() to count the letter "r" in a user-defined string and then compare it with a manual loop count.
  • Write a PHP script to count the letter "r" in a string and highlight each occurrence in the output, marking its index position.

Go to:


PREV : Two-Digit Decimal Combinations.
NEXT : Create Multiplication Table with For Loops.

PHP Code Editor:



Have another way to solve this solution? 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.