Open In App

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:

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 = "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.




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

Output:

:-)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.




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

Output:

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.




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

Output:

Geeks for geeks Contribute

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


Article Tags :