PHP str_pad: How to Pad a String to a Certain Length

In PHP, formatting strings to a specific length is a common requirement for aligning text, generating serial numbers, or creating fixed-width data files. This article explains how to use the built-in str_pad() function to pad a string with other characters until it reaches a desired length. You will learn the function’s syntax, its parameters, and practical examples of padding to the left, right, and both sides of a string.

The str_pad() Function Syntax

The str_pad() function takes an input string and pads it to a new length. The basic syntax is:

str_pad(
    string $string, 
    int $length, 
    string $pad_string = " ", 
    int $pad_type = STR_PAD_RIGHT
): string

Parameters


Practical Examples

1. Pad a String to the Right (Default)

By default, str_pad() adds spaces to the right side of the string.

$string = "Hello";
$result = str_pad($string, 10);

echo "'$result'"; 
// Output: 'Hello     ' (5 spaces added to the right)

You can also specify a custom padding character, such as a dot:

$string = "Hello";
$result = str_pad($string, 10, ".");

echo $result; 
// Output: Hello.....

2. Pad a String to the Left (Leading Zeros)

To pad a string to the left, use the STR_PAD_LEFT constant. This is highly useful for formatting numbers, invoice IDs, or dates with leading zeros.

$invoice_id = "42";
$padded_id = str_pad($invoice_id, 6, "0", STR_PAD_LEFT);

echo $padded_id; 
// Output: 000042

3. Pad Both Sides (Centering Text)

To center-align a string within a block of padding, use STR_PAD_BOTH.

$title = "Title";
$padded_title = str_pad($title, 11, "-", STR_PAD_BOTH);

echo $padded_title; 
// Output: ---Title---

4. Using Multiple Characters for Padding

If your $pad_string is longer than one character, the function will repeat it as necessary, truncating the last repetition if it exceeds the target length.

$string = "PHP";
$result = str_pad($string, 10, "123");

echo $result; 
// Output: PHP1231231