Encodera

Thanks for reading!

Donate to the site — we work hard for you.

PHP reference

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): string

Parameters

ParameterTypeDescription
$stringstringThe source string.
$lengthintThe desired length of the result.
$pad_stringstringOptional. What to pad with; a space by default.
$pad_typeintOptional. `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:

007

Aligning in a column:

<?php
 
echo str_pad('Tea', 10, '.'), '250', "\n";
echo str_pad('Coffee', 10, '.'), '400';

Output:

Tea.......250
Coffee....400

Notes

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.

Thanks for reading!

Donate to the site — we work hard for you.