w3resource

PHP Exercises: Create a new string using first two characters of a given string

PHP Basic Algorithm: Exercise-62 with Solution

Write a PHP program to create a new string using first two characters of a given string. If the string length is less than 2 then return the original string.

Sample Solution:

PHP Code :

<?php
// Define a function named 'test' that extracts the first two characters of a string
function test($s1)
{
    // Check if the length of s1 is less than 2
    if (strlen($s1) < 2)
    {
        // If true, return s1 as is
        return $s1;
    }
    else
    {
        // If false, use substr to extract the first two characters of s1
        return substr($s1, 0, 2);
    }
}

// Test the 'test' function with different input strings and display the results
echo test("Hello")."\n";
echo test("Hi")."\n";
echo test("H")."\n";
echo test("  ")."\n";
?>

Sample Output:

He
Hi
H

Flowchart:

Flowchart: Create a new string using first two characters of a given string.

PHP Code Editor:

Contribute your code and comments through Disqus.

Previous: Write a PHP program to create a new string using three copies of the last two character of a given string of length atleast two.
Next: Write a PHP program to create a new string of the first half of a given string of even length.

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.