PHP 8 reference · String Functions

PHP str_pad() Function

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

PHP 8 Since 4.0

Create a free account to save this page, take notes and track your progress. Sign in

Syntax

str_pad(string $string, int $length, string $pad_string = " ", int $pad_type = STR_PAD_RIGHT): string

Parameters

ParameterDescription
string The input string.
length The final length in bytes. If it's not longer than the string, nothing is added.
pad_string optional What to pad with; it's cut short if needed. Default: " "
pad_type optional STR_PAD_RIGHT, STR_PAD_LEFT or STR_PAD_BOTH. Default: STR_PAD_RIGHT

Return value

The padded string.

Examples

Zero-pad and centerTry it yourself
<?php
echo str_pad("7", 3, "0", STR_PAD_LEFT), "\n";
echo str_pad("42", 6, "*", STR_PAD_BOTH), "\n";

Output

007
**42**
Line up columnsTry it yourself
<?php
foreach (["Tea" => 3.5, "Cake" => 12] as $item => $price) {
    echo str_pad($item, 8, "."), str_pad(number_format($price, 2), 7, " ", STR_PAD_LEFT), "\n";
}

Output

Tea.....   3.50
Cake....  12.00

Common mistakes

  • Lengths are in bytes, so text with é or ü comes out too short. Use mb_str_pad() (PHP 8.3+).
  • For numbers, sprintf("%03d", $n) is often clearer than str_pad().

Version history

VersionChange
PHP 4.0Added

In other languages

Was this page helpful?