w3resource

PHP Exercises: Check whether a given string starts with "F" or ends with "B"

PHP Basic Algorithm: Exercise-45 with Solution

Write a PHP program to check whether a given string starts with "F" or ends with "B". If the string starts with "F" return "Fizz" and return "Buzz" if it ends with "B" If the string starts with "F" and ends with "B" return "FizzBuzz". In other cases return the original string.

Sample Solution:

PHP Code :

<?php
// Define a function that checks the given string for specific conditions and returns corresponding values
function test($s)
{
    // Check if the first character is "F" AND the last character is "B"
    // If true, return "FizzBuzz"
    if ((substr($s, 0, 1) == "F") && (substr($s, strlen($s) - 1, 1) == "B")) {
        return "FizzBuzz";
    }
    // Check if the first character is "F"
    // If true, return "Fizz"
    else if (substr($s, 0, 1) == "F") {
        return "Fizz";
    }
    // Check if the last character is "B"
    // If true, return "Buzz"
    else if (substr($s, strlen($s) - 1, 1) == "B") {
        return "Buzz";
    }
    // If none of the conditions are met, return the original string
    else {
        return $s;
    }
}

// Test the function with different strings
echo test("FizzBuzz")."\n";
echo test("Fizz")."\n";
echo test("Buzz")."\n";
echo test("Founder")."\n";
?>

Explanation:

  • Function Definition:
    • The test function checks the input string $s to see if it meets certain conditions based on its first and last characters.
  • Conditions Checked:
    • First Condition: If the first character of $s is "F" and the last character is "B", it returns "FizzBuzz".
    • Second Condition: If only the first character is "F", it returns "Fizz".
    • Third Condition: If only the last character is "B", it returns "Buzz".
    • Else: If none of the conditions are met, it returns the original string $s.

Output:

Fizz
Fizz
Buzz
Fizz

Visual Presentation:

PHP Basic Algorithm Exercises: Check whether a given string starts with 'F' or ends with 'B'.

Flowchart:

Flowchart: Check whether a given string starts with 'F' or ends with 'B'.

PHP Code Editor:

Contribute your code and comments through Disqus.

Previous: Write a PHP program to compute the sum of the two given integers. If one of the given integer value is in the range 10..20 inclusive return 18.
Next: Write a PHP program to check if it is possible to add two integers to get the third integer from three given integers.

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://w3resource.com/php-exercises/basic-algorithm/php-basic-algorithm-exercise-45.php