PHP str_pad()
The str_pad() method returns a string with a new length by making it longer.
Syntax
str_pad($string, $length, $pad_string, $pad_type)
The str_pad() function has two required parameters and two optional parameters:
$string: Specifies thestringto make longer.$length: Specifies the length of the return string. If the value of$lengthis negative, less than, or equal to the length of the input string, no padding takes place, and$stringwill be returned.$pad_string: Specifies the string to use for padding. If it’s not declared, it defaults to whitespace.$pad_type: Specifies what side to pad the string. The value can beSTR_PAD_BOTH,STR_PAD_LEFT, orSTR_PAD_RIGHT. If it’s not declared, it defaults toSTR_PAD_RIGHT.
The str_pad() function returns a string containing the given $string with a new length based on $length, combining of the given $string with the $pad_string that can be added to the right, left, or both sides of $string.
Example
The following example uses the str_pad() function to add period symbols "." to the right side of the string "hello" until the string has the length of 30:
<?phpecho str_pad("hello", 30, ".", STR_PAD_RIGHT);?>
The example will result in the following output:
hello.........................
Codebyte Example
This example is runnable and uses the str_pad() function:
Note: The final echo statement will return the original string to the console due to the second argument of
str_pad()being set to4which means that the length of the output string is less than the original string.
Contribute to Docs
- Learn more about how to get involved.
- Edit this page on GitHub to fix an error or make an improvement.
- Submit feedback to let us know how we can improve Docs.
Learn PHP on Codecademy
- Looking for an introduction to the theory behind programming? Master Python while learning data structures, algorithms, and more!
- Includes 6 Courses
- With Professional Certification
- Beginner Friendly.75 hours