w3resource

PHP Exercises: Concat two given strings. If the given strings have different length remove the characters from the longer string

PHP Basic Algorithm: Exercise-81 with Solution

Write a PHP program to concat two given strings. If the given strings have different length remove the characters from the longer string.

Sample Solution:

PHP Code :

<?php
// Define a function named 'test' that concatenates two strings in a specific way
// The resulting string will have the length of the longer input string
function test($s1, $s2)
{ 
    // Check if the length of $s1 is less than the length of $s2
    if (strlen($s1) < strlen($s2))
    {
        // Concatenate $s1 with the end portion of $s2 to make their lengths equal
        return $s1 . substr($s2, strlen($s2) - strlen($s1));
    }
    // Check if the length of $s1 is greater than the length of $s2
    else if (strlen($s1) > strlen($s2))
    {
        // Concatenate the end portion of $s1 with $s2 to make their lengths equal
        return substr($s1, strlen($s1) - strlen($s2)) . $s2;
    }
    // If lengths are equal, simply concatenate the two strings
    else
    {
        return $s1 . $s2;
    }
}

// Test the 'test' function with different pairs of strings, then display the results
echo test("abc", "abcd") . "\n";
echo test("Python", "Python") . "\n";
echo test("JS", "Python") . "\n";
?>

Sample Output:

abcbcd
PythonPython
JSon

Flowchart:

Flowchart: Concat two given strings. If the given strings have different length remove the characters from the longer string.

PHP Code Editor:

Contribute your code and comments through Disqus.

Previous: Write a PHP program to check whether the first two characters and last two characters of a given string are same.
Next: Write a PHP program to create a new string using 3 copies of the first 2 characters of a given string. If the length of the given string is less than 2 use the whole 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.