Skip to content
Tutorials Center
My learning

Topics

PHP Reference ยท String Functions

PHP str_pad() function

Reference for PHP str_pad(): pad a string to a target length on the left, right or both sides with any padding text, and avoid multibyte surprises.

str_pad() extends a string to a target length by adding padding characters. You can pad on the right (the default), on the left, or on both sides, which centers the text.

It never shortens a string: if the input is already as long as the requested length, it is returned unchanged. The length is counted in bytes, so accented or non-Latin text needs extra care.

PHP
<?php
echo str_pad("7", 3, "0", STR_PAD_LEFT);  // 007
echo str_pad("Hi", 6, "-", STR_PAD_BOTH); // --Hi--

Try it

PHP Left, right and both

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

PHP A text table and zero-padded numbers

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

Syntax

PHP
str_pad(
    string $string,
    int $length,
    string $pad_string = " ",
    int $pad_type = STR_PAD_RIGHT
): string
Name Description
$string The input string.
$length The desired total length in bytes. If it is less than or equal to the input length, nothing is added.
$pad_string The text used for padding, repeated and cut as needed. Defaults to a space.
$pad_type STR_PAD_RIGHT (default), STR_PAD_LEFT or STR_PAD_BOTH.

Return value: the padded string.

Errors: throws a ValueError if $pad_string is empty or $pad_type is invalid.

Usage notes

  • Odd padding with STR_PAD_BOTH: when the padding cannot be split evenly, the extra character goes on the right.
  • Bytes, not characters. str_pad("รฉ", 4) adds only two spaces, because รฉ is two bytes in UTF-8. For aligned multibyte text use mb_str_pad() (added in PHP 8.3), or build the padding yourself with mb_strlen() and str_repeat().
  • Numbers must be strings or will be converted; cast explicitly for clarity.
  • For columns of formatted text, sprintf() with %-10s or %05d is often shorter.
  • Longer pad strings are repeated and truncated at the end to hit the exact length.