w3resource

PHP Exercises: Create a new string from a given string after swapping last two characters

PHP Basic Algorithm: Exercise-78 with Solution

Write a PHP program to create a new string from a given string after swapping last two characters.

Sample Solution:

PHP Code :

<?php
// Define a function named 'test' that manipulates a string based on its length
function test($s1)
{ 
    // Check if the length of $s1 is greater than 1
    if (strlen($s1) > 1)
    {
        // If true, return a modified string:
        // Concatenate the substring of $s1 from the beginning to the second-to-last character,
        // then append the last character, and finally, append the second-to-last character
        return substr($s1, 0, strlen($s1) - 2) . substr($s1, strlen($s1) - 1, 1) . substr($s1, strlen($s1) - 2, 1);
    }
    else
    {
        // If false (length is less than or equal to 1), return $s1 as is
        return $s1;
    }
}

// Test the 'test' function with different strings, then display the results using echo
echo test("Hello")."\n";
echo test("Python")."\n";
echo test("PHP")."\n";
echo test("JS")."\n";
echo test("C")."\n";
?>

Sample Output:

Helol
Pythno
PPH
SJ
C

Flowchart:

Flowchart: Create a new string from a given string after swapping last two characters.

PHP Code Editor:

Contribute your code and comments through Disqus.

Previous: Write a PHP program to concat two given strings (lowercase). If there are any double character in new string then omit one character.
Next: Write a PHP program to check if a given string begins with 'abc' or 'xyz'. If the string begins with 'abc' or 'xyz' return 'abc' or 'xyz' otherwise return the empty string.

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.