In Trimming PHP Strings you learned how to remove unwanted whitespace characters from around a string. The opposite of trimming is padding — adding extra characters to either end (or both ends) of a string to make the string a certain length.
Padding is handy for lining up strings vertically for display, for adding leading zeroes to numbers, or for any situation where you need a string to be of a certain fixed length.
In this article you’ll explore PHP’s str_pad()
function for padding strings.
Basic str_pad()
usage
In its basic form, you pass 2 arguments to str_pad()
: the string to pad, and how long you want the string to be after it’s been padded. str_pad()
then returns the string padded with spaces on the right-hand side. For example:
$myString = "Hello there";
// Displays "|Hello there |"
echo '|' . str_pad( $myString, 20 ) . '|';
If you specify a final length that’s shorter than the string to pad then the string is untouched:
$myString = "Hello there";
// Displays "|Hello there|"
echo '|' . str_pad( $myString, 5 ) . '|';
Padding with characters other than spaces
If you want to pad using another character, pass that character as the 3rd argument to str_pad()
:
$myString = "Hello there";
// Displays "|Hello there#########|"
echo '|' . str_pad( $myString, 20, '#' ) . '|';
You can even pass a string of characters to use as padding. str_pad()
will repeat and/or truncate the string as necessary:
$myString = "Hello there";
// Displays "|Hello there123412341|"
echo '|' . str_pad( $myString, 20, '1234' ) . '|';
Padding on the left
To pad the string on the left instead of on the right, pass the flag STR_PAD_LEFT
as the 4th argument to str_pad()
. (The default value for this flag is STR_PAD_RIGHT
.) For example:
$myString = "Hello there";
// Displays "| Hello there|"
echo '|' . str_pad( $myString, 20, ' ', STR_PAD_LEFT ) . '|';
Padding on both sides
You can also pad a string on both sides by passing the flag STR_PAD_BOTH
as the 4th argument. str_pad()
attempts to add padding as evenly as possible to both sides of the string:
$myString = "Hello there";
// Displays "| Hello there |"
echo '|' . str_pad( $myString, 20, ' ', STR_PAD_BOTH ) . '|';
You’ve now looked at how to use PHP’s str_pad()
function to add padding to a string. You’ve seen how to use custom padding characters, and how to pad a string on the left, on the right, or on both sides.
Happy PHP coding!
Dragos Balaceanu says
a usefull article