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
Syntax
str_pad(string $string, int $length, string $pad_string = " ", int $pad_type = STR_PAD_RIGHT): string
Parameters
| Parameter | Description |
|---|---|
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
<?php
echo str_pad("7", 3, "0", STR_PAD_LEFT), "\n";
echo str_pad("42", 6, "*", STR_PAD_BOTH), "\n";
Output
007 **42**
<?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 thanstr_pad().
Version history
| Version | Change |
|---|---|
| PHP 4.0 | Added |
In other languages
str.ljust()· Pythonstr.rjust()· Pythonstr.center()· Pythonstring.padStart()· JavaScriptstring.padEnd()· JavaScript
Related
mb_str_pad()· Pad a multibyte string to a given length in characters, on the left, right or both sides. Added in PHP 8.3.sprintf()· Return a formatted string built from a template with placeholders like %s, %d and %.2f. Format numbers, pad and align.str_repeat()· Repeat a string a given number of times and return the result. A count of 0 returns an empty string.- PHP Strings · tutorial