w3resource

PHP Exercises: Check if a given string contains between 2 and 4 'z' character

PHP Basic Algorithm: Exercise-22 with Solution

Write a PHP program to check if a given string contains between 2 and 4 'z' character.

Sample Solution:

PHP Code :

<?php
// Define a function that checks if a string contains the character 'z' 2 to 3 times
function test($s) 
{
    // Initialize a counter variable
    $ctr = 0;

    // Loop through each character in the string
    for ($i = 0; $i < strlen($s); $i++)
    {
        // Check if the current character is 'z' and increment the counter if true
        if (substr($s, $i, 1) == 'z')
        {
            $ctr++;
        }
    }

    // Return true if the counter is greater than 1 and less than 4, indicating 'z' occurs 2 to 3 times
    return $ctr > 1 && $ctr < 4;
}

// Test the function with different strings
var_dump(test("frizz"));
var_dump(test("zane"));
var_dump(test("Zazz"));
var_dump(test("false"));
?>

Explanation:

  • Function Definition:
    • The test function takes a string parameter $s and checks if it contains the character 'z' exactly 2 or 3 times.
  • Counter Initialization:
    • A counter variable $ctr is initialized to 0. This counter will track the occurrences of 'z'.
  • Loop through Each Character:
    • A for loop iterates over each character in the string $s.
    • Condition Check:
      • For each character, it checks if it is 'z'.
      • If it is, the counter $ctr is incremented by 1.
  • Return Condition:
    • After the loop, it returns true if the counter value $ctr is between 2 and 3, inclusive (indicating 2 or 3 occurrences of 'z'). Otherwise, it returns false.

Output:

bool(true)
bool(false)
bool(true)
bool(false)

Visual Presentation:

PHP Basic Algorithm Exercises: Check if a given string contains between 2 and 4 'z' character.

Flowchart:

Flowchart: Check if a given string contains between 2 and 4 'z' character.

PHP Code Editor:

Contribute your code and comments through Disqus.

Previous: Write a PHP program to find the larger value from two positive integer values that is in the range 20..30 inclusive, or return 0 if neither is in that range.
Next: Write a PHP program to check if two given non-negative integers have the same last digit.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Become a Patron!

Follow us on Facebook and Twitter for latest update.

It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.

https://www.w3resource.com/php-exercises/basic-algorithm/php-basic-algorithm-exercise-22.php