In PHP, str_pad() pads a string to a given length by adding characters to the left, right, or both sides.
It is great for aligning text, adding leading zeros to numbers, or building simple text tables.
Syntax
Call str_pad() with the values you need. Start with this line.
PHP
$padded = str_pad("42", 5, "0", STR_PAD_LEFT);
Call
What it does
str_pad("42", 5, "0", STR_PAD_LEFT)
Returns "00042".
str_pad("Hi", 6, "*")
Returns "Hi****" (pads on the right by default).
str_pad("PHP", 9, "-=", STR_PAD_BOTH)
Returns "-=-PHP-=-".
The pad type can be STR_PAD_RIGHT (default), STR_PAD_LEFT, or STR_PAD_BOTH. If the target length is not larger than the string, the string is returned unchanged.
Library declarations
PHP
str_pad(string $string, int $length, string $pad_string = " ", int $pad_type = STR_PAD_RIGHT): string
Parameters
Parameter
Description
string
Required. The input string to pad.
length
Required. The final length you want. If it is smaller than the string, nothing is added.
pad_string
Optional. The text used for padding. Default is a space. It cannot be empty.
pad_type
Optional. STR_PAD_RIGHT (default), STR_PAD_LEFT, or STR_PAD_BOTH.