w3resource

PHP Exercises: Create a new string taking the first character from a given string and the last character from another given string

PHP Basic Algorithm: Exercise-76 with Solution

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.

Sample Solution:

PHP Code :

<?php
// Define a function named 'test' that extracts the first and last characters from two input strings
function test($s1, $s2)
{ 
    // Initialize an empty string to store the last characters
    $lastChars = "";

    // Check if the first string has a length greater than 0
    if (strlen($s1) > 0)
    {
        // If true, append the first character of $s1 to $lastChars
        $lastChars = $lastChars.substr($s1, 0, 1);
    }
    else
    {
        // If false, append "#" to $lastChars
        $lastChars = $lastChars."#";
    }

    // Check if the second string has a length greater than 0
    if (strlen($s2) > 0)
    {
        // If true, append the last character of $s2 to $lastChars
        $lastChars = $lastChars.substr($s2, strlen($s2) - 1);
    }
    else
    {
        // If false, append "#" to $lastChars
        $lastChars = $lastChars."#";
    }

    // Return the concatenated string containing the last characters
    return $lastChars;
}

// Test the 'test' function with different strings, then display the results using echo
echo test("Hello", "Hi")."\n";
echo test("Python", "PHP")."\n";
echo test("JS", "JS")."\n";
echo test("Csharp", "")."\n";
?>

Sample Output:

Hi
PP
JS
C#

Flowchart:

Flowchart: Create a new string taking the first character from a given string and the last character from another given string.

PHP Code Editor:

Contribute your code and comments through Disqus.

Previous: Write a PHP program to create a new string of length 2, using first two characters of a given string. If the given string length is less than 2 use '#' as missing characters.
Next: Write a PHP program to concat two given strings (lowercase). If there are any double character in new string then omit one 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.