PHP Exercises: Create a new string taking the first 3 characters of a given string and return the string with the 3 characters added at both the front and back
PHP Basic Algorithm: Exercise-11 with Solution
Write a PHP program to create a new string taking the first 3 characters of a given string and return the string with the 3 characters added at both the front and back. If the given string length is less than 3, use whatever characters are there.
Sample Solution:
PHP Code :
<?php
// Define a function named "test" that takes a parameter $str
function test($str)
{
// Use an if-else statement to check if the length of $str is less than 3
if (strlen($str) < 3) {
// If true, concatenate $str with itself twice and return the result
return $str . $str . $str;
} else {
// If false, use substr to get the first three characters of $str
$front = substr($str, 0, 3);
// Concatenate $front, $str, and $front, then return the result
return $front . $str . $front;
}
}
// Call the test function with argument "Python" and echo the result
echo test("Python") . "\n";
// Call the test function with argument "JS" and echo the result
echo test("JS") . "\n";
// Call the test function with argument "Code" and echo the result
echo test("Code") . "\n";
?>
Sample Output:
PytPythonPyt JSJSJS CodCodeCod
Visual Presentation:
Flowchart:
PHP Code Editor:
Contribute your code and comments through Disqus.
Previous: Write a PHP program to create a new string with the last char added at the front and back of a given string of length 1 or more.
Next: Write a PHP program to check if a given string starts with 'C#' or not.
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