PHP str_pad: How to Pad a String to a Certain Length
In PHP, formatting strings to a specific length is a common
requirement for aligning text, generating serial numbers, or creating
fixed-width data files. This article explains how to use the built-in
str_pad() function to pad a string with other characters
until it reaches a desired length. You will learn the function’s syntax,
its parameters, and practical examples of padding to the left, right,
and both sides of a string.
The str_pad() Function Syntax
The str_pad() function takes an input string and pads it
to a new length. The basic syntax is:
str_pad(
string $string,
int $length,
string $pad_string = " ",
int $pad_type = STR_PAD_RIGHT
): stringParameters
$string: The original input string you want to pad.$length: The target length of the final string. If this value is less than or equal to the length of the input string, no padding takes place, and the original string is returned.$pad_string: The character or characters to use for padding. The default is a single space" ".$pad_type: Determines where to add the padding. It accepts one of three PHP constants:STR_PAD_RIGHT(Default): Adds padding to the right end of the string.STR_PAD_LEFT: Adds padding to the left end of the string (useful for leading zeros).STR_PAD_BOTH: Distributes padding evenly to both sides. If the padding count is odd, the right side gets the extra padding.
Practical Examples
1. Pad a String to the Right (Default)
By default, str_pad() adds spaces to the right side of
the string.
$string = "Hello";
$result = str_pad($string, 10);
echo "'$result'";
// Output: 'Hello ' (5 spaces added to the right)You can also specify a custom padding character, such as a dot:
$string = "Hello";
$result = str_pad($string, 10, ".");
echo $result;
// Output: Hello.....2. Pad a String to the Left (Leading Zeros)
To pad a string to the left, use the STR_PAD_LEFT
constant. This is highly useful for formatting numbers, invoice IDs, or
dates with leading zeros.
$invoice_id = "42";
$padded_id = str_pad($invoice_id, 6, "0", STR_PAD_LEFT);
echo $padded_id;
// Output: 0000423. Pad Both Sides (Centering Text)
To center-align a string within a block of padding, use
STR_PAD_BOTH.
$title = "Title";
$padded_title = str_pad($title, 11, "-", STR_PAD_BOTH);
echo $padded_title;
// Output: ---Title---4. Using Multiple Characters for Padding
If your $pad_string is longer than one character, the
function will repeat it as necessary, truncating the last repetition if
it exceeds the target length.
$string = "PHP";
$result = str_pad($string, 10, "123");
echo $result;
// Output: PHP1231231