PHP Exercises: Concat two given strings
PHP Basic Algorithm: Exercise-77 with Solution
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";
?>
Sample 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