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

Explanation:

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