str_pad
Pads a string to a given length.
Syntax
str_pad(string $string, int $length, string $pad_string = " ", int $pad_type = STR_PAD_RIGHT): stringParameters
| Parameter | Type | Description |
|---|---|---|
| $string | string | The source string. |
| $length | int | The desired length of the result. |
| $pad_string | string | Optional. What to pad with; a space by default. |
| $pad_type | int | Optional. `STR_PAD_LEFT`, `STR_PAD_RIGHT` or `STR_PAD_BOTH`. |
Return value
stringThe padded string.
Examples
Leading zeros in a number:
<?php
echo str_pad('7', 3, '0', STR_PAD_LEFT);Output:
007Aligning in a column:
<?php
echo str_pad('Tea', 10, '.'), '250', "\n";
echo str_pad('Coffee', 10, '.'), '400';Output:
Tea.......250
Coffee....400Notes
If the string is already longer than the given length, it is returned unchanged — nothing is cut off.
See also
- str_repeat — Repeats a string a given number of times.
- sprintf — Returns a string built from a format template.
Related recipes
In the tutorial
- Strings — Working with strings in PHP — quotes, concatenation, length, searching, replacing and multibyte functions.