w3resource

PHP Exercises: Create a new string which is 4 copies of the 2 front characters of a given string

PHP Basic Algorithm: Exercise-8 with Solution

Write a PHP program to create a new string which is 4 copies of the 2 front characters of a given string. If the given string length is less than 2 return the original string.

Sample Solution:

PHP Code :

<?php
// Define a function named "test" that takes a parameter $str
function test($str) 
{
    // Use a ternary operator to check if the length of $str is less than 2
    // If true, return $str as it is
    // If false, concatenate the substring from index 0 to 1 four times and return the result
    return strlen($str) < 2 ? $str : substr($str, 0, 2) . substr($str, 0, 2) . substr($str, 0, 2) . substr($str, 0, 2);
}

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

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

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

Sample Output:

C C C C 
JSJSJSJS
a

Visual Presentation:

PHP Basic Algorithm Exercises: Create a new string which is 4 copies of the 2 front characters of a given string.

Flowchart:

Flowchart: Create a new string which is 4 copies of the 2 front characters of a given string.

PHP Code Editor:

Contribute your code and comments through Disqus.

Previous: Write a PHP program to exchange the first and last characters in a given string and return the new string.
Next: 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.

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.