str_pad()
str_pad() — Pad a string to a certain length with another string.
Built-in function of PHP 8.5. The manual lists it as available in PHP 4 >= 4.0.1, PHP 5, PHP 7, PHP 8. This page is the reference card: signature, parameters and return value, plus the changelog and the example the manual provides.
What it does
This function returns the string string padded on the left, the right, or both sides to the specified padding length. If the optional argument pad_string is not supplied, the string is padded with spaces, otherwise it is padded with characters from pad_string up to the limit.
Signature
str_pad(string $string, int $length, string $pad_string = " ", int $pad_type = STR_PAD_RIGHT): string
Parameters
| Parameter | Type | What it takes |
|---|---|---|
| $string | string | The input string. |
| $length | int | The desired length of the final padded string. If the value of length is negative, less than, or equal to the length of the input string, no padding takes place, and string will be returned. |
| $pad_string | string | The pad_string may be truncated if the required number of padding characters can't be evenly divided by the pad_string's length. |
| $pad_type | int | Optional argument pad_type can be STR_PAD_RIGHT, STR_PAD_LEFT, or STR_PAD_BOTH. If pad_type is not specified it is assumed to be STR_PAD_RIGHT. |
Return value
Returns the padded string.
Example
A runnable snippet:
$input = "Alien"; echo str_pad($input, 10), PHP_EOL; // produces "Alien " echo str_pad($input, 10, "-=", STR_PAD_LEFT), PHP_EOL; // produces "-=-=-Alien" echo str_pad($input, 10, "_", STR_PAD_BOTH), PHP_EOL; // produces "__Alien___" echo str_pad($input, 6, "___"), PHP_EOL; // produces "Alien_" echo str_pad($input, 3, "*"), PHP_EOL; // produces "Alien"
Changelog
| Version | Change |
|---|---|
| 8.0.0 | Now throws a ValueError if padding is needed and pad_string is empty or pad_type is invalid. Previously, an E_WARNING was raised and null was returned. |
See also
All PHP 8.5 built-in functions
Reference card built from the PHP manual page str_pad() (PHP documentation, CC BY 3.0). The page is generated from the manual, so the wording of the parameter and return value text follows php.net.