w3resource

PHP Exercises: Create a new string where 'if' is added to the front of a given string

PHP Basic Algorithm: Exercise-5 with Solution

Write a PHP program to create a new string where 'if' is added to the front of a given string. If the string already begins with 'if', return the string unchanged.

Sample Solution:

PHP Code :

<?php
// Define a function named "test" that takes a parameter $s
function test($s)
{
    // Check if the length of $s is greater than or equal to 2 AND if the substring of $s from index 0 to 1 is equal to "if"
    if (strlen($s) >= 2 && substr($s, 0, 2) == "if")
    {
        // If true, return $s as it is
        return $s;
    }

    // If false, prepend "if " to $s and return the result
    return "if " . $s;
}

// Call the test function with argument "if else" and echo the result
echo test("if else") . "\n";

// Call the test function with argument "else" and echo the result
echo test("else") . "\n";

// Call the test function with argument "if" and echo the result
echo test("if") . "\n";
?>

Explanation:

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-5.php