str_pad

Pads a string to a given length with another string, on the left, right or both sides.

Signature
str_pad(string $string, int $length, string $pad_string = " ", int $pad_type = STR_PAD_RIGHT): string
  • Added in PHP 4.0.1

Parameters

ParameterTypeDescription
$stringstringThe input string.
$lengthintThe desired length in bytes. If it is negative or not greater than the input length, no padding occurs.
$pad_stringoptionalstring= " "The string used for padding. It may be truncated if the required padding is not a whole multiple of its length.
$pad_typeoptionalint= STR_PAD_RIGHTOne of STR_PAD_RIGHT, STR_PAD_LEFT or STR_PAD_BOTH.

Return value

stringThe padded string. If length is less than or equal to the length of string, the input is returned unchanged.

Errors

Throws a ValueError if pad_string is empty or if pad_type is not one of the three STR_PAD_* constants.

str_pad grows a string to a target length by repeating a filler. The default fills with spaces on the right; STR_PAD_LEFT right-aligns, and STR_PAD_BOTH centres.

When to reach for it

Two jobs dominate. First, fixed-width identifiers: str_pad('42', 6, '0', STR_PAD_LEFT) gives 000042 for an invoice or barcode. Second, plain-text alignment — CLI tables, receipts, fixed-width export files that a mainframe or bank expects at exact byte offsets. For number formatting specifically, sprintf('%06d', 42) does the same job and reads better inside a larger template.

What trips people up

Three things. Padding never truncates: if the input is already longer than length, you get it back unchanged, so str_pad alone does not guarantee a fixed width — combine it with substr if the field must be exactly N bytes.

length counts bytes, not characters. A name containing é costs two bytes, so a padded column of UTF-8 text comes out ragged. Use mb_str_pad (PHP 8.3+) for multibyte input.

With STR_PAD_BOTH, an odd amount of padding favours the right side, so centring is not always symmetrical.

Example

Try it yourself
Loading editor…
Press Run to execute the code.

When to use it

  • Zero-pad an order number to a fixed six-digit reference
  • Align a CLI table or plain-text receipt into columns
  • Build fixed-width export records for a bank or legacy import
  • Render a simple text progress bar or separator of a known width

Frequently asked questions

Why does str_pad not shorten a string that is too long?

By design it only ever adds characters; if length is less than or equal to the current length the input is returned unchanged. Combine it with substr when a field must be exactly N bytes.

What is the difference between str_pad and sprintf for zero-padding?

Both work: str_pad('42', 6, '0', STR_PAD_LEFT) and sprintf('%06d', 42) give 000042. sprintf is clearer when the padded value is part of a larger template, str_pad when you are padding an arbitrary string rather than a number.

Why is my UTF-8 text misaligned after str_pad?

str_pad counts bytes, and multibyte characters cost more than one byte each. Use mb_str_pad(), added in PHP 8.3, for character-based padding.

More examples

An aligned plain-text table

Item names are left-padded to 22 columns and prices right-aligned in 8, producing a clean two-column receipt. str_pad('', 30, '-') is also the idiomatic way to draw a rule of an exact width, since padding an empty string just repeats the filler.

Example · php
<?php
$rows = [['Coffee', 3.5], ['Sparkling water', 1.25], ['Tea', 12]];

echo str_pad('', 30, '-'), "\n";
foreach ($rows as [$item, $price]) {
    echo str_pad($item, 22), str_pad(number_format($price, 2), 8, ' ', STR_PAD_LEFT), "\n";
}
echo str_pad('', 30, '-'), "\n";

Padding does not truncate

The first result is 20, not 10: str_pad returned the input untouched because it was already longer than the target. Wrapping it in substr is what actually guarantees a fixed-width field. The last line shows the byte problem — 'café' is 5 bytes in UTF-8, so only one pad character is added even though the text is 4 characters long.

Example · php
<?php
$field = 'AVeryLongProductCode';

$padded = str_pad($field, 10, ' ');
var_dump(strlen($padded));

$fixed = substr(str_pad($field, 10, ' '), 0, 10);
var_dump($fixed, strlen($fixed));

var_dump(strlen(str_pad('café', 6, '.')));

Discussion

  • Be the first to comment on this lesson.