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";
?>

Sample 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.



Follow us on Facebook and Twitter for latest update.