w3resource

PHP Exercises: Create a new string from two given string one is shorter and another is longer


65. Concat Shorter into Longer

Write a PHP program to create a new string from two given string one is shorter and another is longer. The format of the new string will be long string + short string + long string.

Sample Solution:

PHP Code :

<?php
// Define a function named 'test' that concatenates strings based on their lengths
function test($s1, $s2)
{ 
    // Use a ternary operator to determine the order of concatenation
    return strlen($s1) < strlen($s2) ? $s2 . $s1 . $s2 : $s1 . $s2 . $s1;
}

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

Explanation:

  • Function Definition:
    • The function test takes two string parameters, $s1 and $s2.
  • Concatenation Based on Length:
    • The function uses a ternary operator to concatenate the strings in different orders based on their lengths:
      • If the length of $s1 is less than $s2, it returns $s2 . $s1 . $s2 (places $s1 between two instances of $s2).
      • Otherwise, it returns $s1 . $s2 . $s1 (places $s2 between two instances of $s1).

Output:

HelloHiHello
PythonJSPython

Flowchart:

Flowchart: Create a new string from two given string one is shorter and another is longer.

For more Practice: Solve these Related Problems:

  • Write a PHP script to combine two strings by sandwiching the shorter string between two copies of the longer string.
  • Write a PHP function to determine the lengths of two strings and concatenate them in a long-short-long order.
  • Write a PHP program to compare string lengths and format a new string as long + short + long, ensuring proper case preservation.
  • Write a PHP script to analyze two inputs and output a composite string following the pattern: longer string, then shorter, then longer again.

PHP Code Editor:



Contribute your code and comments through Disqus.

Previous: Write a PHP program to create a new string without the first and last character of a given string of length atleast two.
Next: Write a PHP program to concat two given string of length atleast 1, after removing their first character.

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.