PHP Exercises: Concat two given strings
Write a PHP program to concat two given strings (lowercase). If there are any double character in new string then omit one character.
Sample Solution:
PHP Code :
<?php
// Define a function named 'test' that concatenates two strings based on certain conditions
function test($s1, $s2)
{
// Check if the length of $s1 is less than 1
if (strlen($s1) < 1)
{
// If true, return $s2
return $s2;
}
// Check if the length of $s2 is less than 1
if (strlen($s2) < 1)
{
// If true, return $s1
return $s1;
}
// Check if the last character of $s1 is not equal to the first character of $s2
if (substr($s1, strlen($s1) - 1, 1) <> substr($s2, 0, 1))
{
// If true, concatenate $s1 and $s2
return $s1 . $s2;
}
else
{
// If false, concatenate $s1 and the substring of $s2 from the second character
return $s1 . substr($s2, 1, strlen($s1) - 1);
}
}
// Test the 'test' function with different strings, then display the results using echo
echo test("abc", "cat")."\n";
echo test("Python", "PHP")."\n";
echo test("php", "php")."\n";
?>
Explanation:
- Function Definition:
- The test function is defined with two parameters:
- $s1: the first input string.
- $s2: the second input string.
- Condition 1: Check if $s1 is Empty:
- If $s1 has less than 1 character (i.e., it is empty):
- Return $s2.
- Condition 2: Check if $s2 is Empty:
- If $s2 has less than 1 character (i.e., it is empty):
- Return $s1.
- Condition 3: Check the Last Character of $s1 and the First Character of $s2:
- If the last character of $s1 is not equal to the first character of $s2:
- Concatenate $s1 and $s2 directly.
- Otherwise (if they are equal):
- Concatenate $s1 with $s2, excluding the first character of $s2 (to avoid duplication).
Output:
abcat PythonPHP phphp
Flowchart:
PHP Code Editor:
Contribute your code and comments through Disqus.
Previous: Write a PHP program to create a new string taking the first character from a given string and the last character from another given string. If the length of any given string is 0, use '#' as its missing character.
Next: Write a PHP program to create a new string from a given string after swapping last two characters.
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics