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.


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

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

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.

   $str = "Geeks for geeks";
   echo str_pad($str, 21, ":-)", STR_PAD_BOTH); 


:-)Geeks for geeks:-)

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

   $str = "Geeks for geeks";
   echo str_pad($str, 25, "Contribute", STR_PAD_LEFT); 


ContributeGeeks for geeks

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

   $str = "Geeks for geeks";
   echo str_pad($str, 26, " Contribute", STR_PAD_RIGHT); 


Geeks for geeks Contribute


This article is attributed to GeeksforGeeks.org

leave a comment



load comments

Subscribe to Our Newsletter