str_pad() / str_repeat() Since: PHP 4(2000)
Pads a string to a specified length with another string, or repeats a string a given number of times. Useful for generating fixed-width data and formatting text output.
Syntax
// Pads a string to the specified length. str_pad($string, $length, $pad_string, $pad_type); // Repeats a string the specified number of times. str_repeat($string, $times);
Functions
| Function | Description |
|---|---|
| str_pad($string, $length, $pad_string, $pad_type) | Pads $string with $pad_string until it reaches $length characters. Use $pad_type to control the direction: STR_PAD_RIGHT pads the right side, STR_PAD_LEFT pads the left side, and STR_PAD_BOTH pads both sides. |
| str_repeat($string, $times) | Returns $string repeated $times times. |
Return Value
str_pad() returns the padded string. If the original string is already equal to or longer than the specified length, it is returned unchanged. str_repeat() returns the repeated string.
Sample Code
<?php
// Pads the right side with spaces. Right-padding is the default behavior.
echo str_pad("PHP", 10); // Outputs "PHP " — 7 spaces are added.
// Pads the left side with zeros.
echo str_pad("42", 5, "0", STR_PAD_LEFT); // Outputs "00042".
// Pads both sides with hyphens.
echo str_pad("Title", 20, "-", STR_PAD_BOTH); // Hyphens are added on both sides.
// You can use a multi-character pad string.
echo str_pad("1", 10, "=-", STR_PAD_RIGHT); // Outputs "1=-=-=-=-=-" — the pad string repeats.
// Repeat a string with str_repeat().
echo str_repeat("*", 10); // Outputs "**********".
// Useful for generating separator lines.
echo str_repeat("-", 40); // Outputs a line of 40 hyphens.
// Useful for generating indentation.
$depth = 3;
$indent = str_repeat(" ", $depth);
echo $indent . "Nested item"; // Outputs the string preceded by 6 spaces.
// Zero-padding an order number.
$order_id = 157;
echo "ORD-" . str_pad($order_id, 6, "0", STR_PAD_LEFT); // Outputs "ORD-000157".
// Right-aligning prices in a list.
$items = ["Apple" => 150, "Orange" => 80, "Grape" => 500];
foreach ($items as $name => $price) {
echo str_pad($name, 10) . str_pad($price, 6, " ", STR_PAD_LEFT) . "\n";
}
Notes
str_pad() pads a string with another character until it reaches the specified length. The fourth argument controls the direction: STR_PAD_RIGHT pads the right, STR_PAD_LEFT pads the left, and STR_PAD_BOTH pads both sides. When omitted, STR_PAD_RIGHT is used.
To zero-pad an order number, use str_pad($id, 6, "0", STR_PAD_LEFT) — this produces the same result as %06d in sprintf(). It is also handy for text formatting and generating fixed-width data for CSV output.
str_repeat() repeats a string a specified number of times and is useful for creating separator lines or indentation. Passing 0 returns an empty string; passing a negative value causes an error. For format-based string building, see sprintf(). For extracting substrings, see substr().
If you find any errors or copyright issues, please contact us.