01 · THE IDEAREAD → TRY → LEARN
Why pad strings?
Text output often needs columns: a name followed by dots, a number with leading zeros, or a title centered in a banner. str_pad() handles these cases without a manual loop. It takes a string and a target length, then adds characters until the string reaches that length.
The PHP 8.4 signature is str_pad(string $string, int $length, string $pad_string = " ", int $pad_type = STR_PAD_RIGHT): string. It always returns a new string. The original value is never modified.
The four arguments
$stringis the text to extend.$lengthis the desired final length, not the number of characters to add.$pad_stringsupplies the filler. The default is a single space.$pad_typechooses the side:STR_PAD_RIGHT(the default),STR_PAD_LEFT, orSTR_PAD_BOTH.
The naming of the constants matters. STR_PAD_RIGHT puts padding on the right, so the original text stays on the left. A label that is "left aligned" therefore uses STR_PAD_RIGHT. Mixing these up is the most common mistake with this function.
A first look
The example below shows left padding with a two-character filler, centered padding, and a filler that must be cut off to fit.
$input = "Alien";
echo str_pad($input, 10, "-=", STR_PAD_LEFT), PHP_EOL;
echo str_pad($input, 10, "_", STR_PAD_BOTH), PHP_EOL;
echo str_pad($input, 6, "___"), PHP_EOL;-=-=-Alien __Alien___ Alien_
With STR_PAD_BOTH, five padding characters are needed. They cannot be split evenly, so the right side gets the extra one. A multi-character filler is repeated and cut off when it does not fit exactly.
No padding and no truncation
If $length is less than or equal to the current length, or is negative, you get the original string back. str_pad() never shortens text. If a column must have a strict maximum, you need a separate step such as substr() before padding.
The length is measured in bytes. For plain ASCII this equals the number of characters. Multibyte text is a different topic, and this lesson stays with ASCII labels.
An empty $pad_string or an invalid $pad_type raises a ValueError, so do not pass those values from untrusted input without checking them.
Building a small table
Padding is most useful when several lines must line up. Names are padded on the right with dots, and quantities are padded on the left with spaces so the digits line up.
$items = ["Tea" => 3, "Coffee" => 12, "Milk" => 5];
foreach ($items as $name => $qty) {
echo str_pad($name, 8, ".") . str_pad((string) $qty, 3, " ", STR_PAD_LEFT), PHP_EOL;
}Tea..... 3 Coffee.. 12 Milk.... 5
str_pad() expects a string, so the integer quantity is cast first. Otherwise, a file without strict types would coerce it silently, and one with strict types would raise a TypeError.
Edge cases in one place
The next example gathers several behaviors into a JSON array: a target that is too small, a negative target, zero-padding for a number, a repeated line with str_repeat(), and an uneven centered pad.
$result = [
str_pad("abc", 2),
str_pad("abc", -1, "*"),
str_pad("7", 3, "0", STR_PAD_LEFT),
str_repeat("=", 5),
str_pad("ab", 7, "xyz", STR_PAD_BOTH),
];
echo json_encode($result, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES), PHP_EOL;["abc","abc","007","=====","xyabxyz"]
Notice the last value. Five characters are added, two on the left (xy) and three on the right (xyz). When padding is uneven, the right side is always the larger one.
Common mistakes
- Thinking
$lengthis the amount of padding to add. - Reversing the meaning of
STR_PAD_LEFTandSTR_PAD_RIGHT. - Expecting long text to be cut down to
$length. - Forgetting that centered padding favors the right side.
- Passing an empty filler string.
Exercise contract
Write a function padLabel(string $label, int $width, string $align): string. It must pad the label with . characters to exactly $width bytes when the label is shorter than that. The alignment rules are:
"left"keeps the text on the left, so the dots go on the right."right"keeps the text on the right, so the dots go on the left."center"splits the dots, with any extra dot going on the right.- Any other alignment value behaves like
"left".
If the label is already as wide as $width or wider, return it unchanged. The tests check the returned string, so do not echo anything. A match expression that converts the alignment name into a STR_PAD_* constant keeps the function short and easy to read.
Recap
str_pad() extends a string to a target length using a filler and a side. It never truncates, it measures bytes, and STR_PAD_RIGHT means the text stays on the left. Use str_repeat() when you need a plain run of one string, such as a divider line.
Functions · Arrays · Types
- Build fixed-width ASCII labels
- Implement and test a deterministic PHP 8.4 function