PHP str_pad() Function

The str_pad() function is a built-in function in PHP and is used to pad a string to a given length. We can pad the input string by any other string up to a specified length. If we do not pass the other string to the str_pad() function then the input string will be padded by spaces.

Syntax :

string str_pad($string, $length, $pad_string, $pad_type)

Parameters: This function accepts four parameters as shown in the above syntax out of which first two are mandatory to be supplied and rest two are optional. All of these parameters are described below:

  • $string: This parameter is mandatory. It specifies the input string which is needed to be padded.
  • $length: This parameter is also mandatory. It specifies the length of the new string that will be generated after padding the input string $string. If this length is less than or equals the length of input string then no padding will be done.
  • $pad_string: This parameter is optional and its default value is whitespace ‘ ‘. It specifies the string to be used for padding.
  • $pad_type: This parameter is also optional. It specifies which side of the string needs to be padded, i.e. left, right or both. By default it’s value is set to STR_PAD_RIGHT. If we want to pad the left side of the input string then we should set this parameter to STR_PAD_LEFT and if we want to pad both sides then this parameter should be set to STR_PAD_BOTH.

Return Value: This parameter returns a new string obtained after padding the input string $string.

Examples:

Input : $string = "Hello World", $length = 20, 
        $pad_string = "."
Output : Hello World........

Input : $string = "Beginner for Beginner", $length = 18,
        $pad_string = ")"
Output : Beginner for Beginner)))

Below programs illustrate the str_pad() function in PHP:

Program 1: In this program we will pad to both the sides of the input string by setting last parameter to STR_PAD_BOTH. If the padding length is not an even number, the right side gets the extra padding.




<?php
   $str = "Beginner for Beginner";
   echo str_pad($str, 21, ":-)", STR_PAD_BOTH); 
?>


Output:

:-)Beginner for Beginner:-)

Program 2: In this program we will pad to left side of the input string by setting last parameter to STR_PAD_LEFT.




<?php
   $str = "Beginner for Beginner";
   echo str_pad($str, 25, "Contribute", STR_PAD_LEFT); 
?>


Output:

ContributeBeginner for Beginner

Program 3: In this program we will pad to right side of the input string by setting last parameter to STR_PAD_RIGHT.




<?php
   $str = "Beginner for Beginner";
   echo str_pad($str, 26, " Contribute", STR_PAD_RIGHT); 
?>


Output:

Beginner for Beginner Contribute

Reference:
http://php.net/manual/en/function.str-pad.php



Contact Us