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

Explanation:

  • Function Definition:
    • The function test takes one parameter, $str.
  • Conditional Check:
    • Uses a ternary operator to check if the length of $str is less than 2:
      • If true:
        • Returns $str as is (for strings with fewer than 2 characters).
      • If false:
        • Takes the first two characters (substr($str, 0, 2)) and repeats this substring four times, then returns the resulting string.
  • Function Calls and Output:
    • First Call: test("C Sharp")
      • Takes "C " and repeats it four times, resulting in "C C C C ".
    • Second Call: test("JS")
      • Takes "JS" and repeats it four times, resulting in "JSJSJSJS".
    • Third Call: test("a")
      • Returns "a" as the string length is less than 2.

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.



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://w3resource.com/php-exercises/basic-algorithm/php-basic-algorithm-exercise-8.php