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";
?>
Sample Output:
if else if else if
Flowchart:
PHP Code Editor:
Contribute your code and comments through Disqus.
Previous: Write a PHP program to check a given integer and return true if it is within 10 of 100 or 200.
Next: Write a PHP program to remove the character in a given position of a given string. The given position will be in the range 0..string length -1 inclusive.
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics