w3resource

PHP Exercises: Move the last two characters to the start of a given string of length at least two

PHP Basic Algorithm: Exercise-68 with Solution

Write a PHP program to move the last two characters to the start of a given string of length at least two.

Sample Solution:

PHP Code :

<?php
// Define a function named 'test' that rearranges the last two characters of a string with the rest of the string
function test($s1)
{ 
    // Use substr to extract substrings and rearrange them
    return substr($s1, strlen($s1) - 2, 2) . substr($s1, 0, strlen($s1) - 2);
}

// Test the 'test' function with different strings and display the results
echo test("Hello")."\n";
echo test("JS")."\n";
?>

Explanation:

  • Function Definition:
    • A function named test is defined, which takes one parameter, $s1, representing the input string.
  • Character Rearrangement:
    • Inside the function, two substr calls are used to rearrange the characters of the input string $s1:
      • substr($s1, strlen($s1) - 2, 2) extracts the last two characters of the string.
      • substr($s1, 0, strlen($s1) - 2) extracts all characters of the string except for the last two.
  • Concatenation:
    • The function returns the concatenation of the last two characters (extracted first) followed by the rest of the string (extracted second), effectively moving the last two characters to the front of the string.

Output:

loHel
JS

Flowchart:

Flowchart: Move the last two characters to the start of a given string of length at least two.

PHP Code Editor:

Contribute your code and comments through Disqus.

Previous: Write a PHP program to move the first two characters to the end of a given string of length at least two.
Next: Write a PHP program to create a new string without the first and last character of a given string of any length.

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