w3resource

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


75. New String of Length 2 with Padding

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.

Sample Solution:

PHP Code :

<?php
// Define a function named 'test' that modifies the input string based on its length
function test($s1)
{ 
  // Check if the length of the string is greater than or equal to 2
  if (strlen($s1) >= 2)
     {
       // If true, extract the first two characters from the string
       $s1 = substr($s1, 0, 2);
      }
  // If the length is greater than 0 but less than 2
  else if (strlen($s1) > 0)
      {
       // Extract the first character and concatenate "#" to it
       $s1 = substr($s1, 0, 1) . "#";
      }
  // If the length is 0
  else
      {
       // Set the string to "##"
       $s1 = "##";
      }
   // Return the modified string
   return $s1;
}

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

Explanation:

  • Function Definition:
    • The test function is defined with a single parameter:
      • $s1: the input string.
  • String Modification Based on Length:
    • The function has three cases based on the length of $s1:
      • If the length is 2 or more:
        • Extracts the first two characters of $s1 using substr($s1, 0, 2).
      • If the length is 1:
        • Extracts the first character and appends a "#" to it, making $s1 = substr($s1, 0, 1) . "#".
      • If the length is 0:
        • Sets $s1 to "##".
  • Return Value:
    • Returns the modified $s1 based on the above conditions.

Output:

He
Py
a#
 #

Flowchart:

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

For more Practice: Solve these Related Problems:

  • Write a PHP script to create a string using the first two characters of an input, padding with '#' if necessary when the string is too short.
  • Write a PHP function to conditionally append '#' characters to an input if its length is less than 2, then output exactly two characters.
  • Write a PHP program to check the length of a string and output either the first two letters or the string supplemented with '#'.
  • Write a PHP script to simulate string padding for inputs of length 0 or 1 to guarantee a two-character result.

Go to:


PREV : Middle 3 Characters from a String.
NEXT : Concat First from One and Last from Another.

PHP Code Editor:



Contribute your code and comments through Disqus.

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.