0
0
PhpHow-ToBeginner · 3 min read

How to Use str_pad in PHP: Syntax and Examples

Use str_pad in PHP to add characters to a string until it reaches a specified length. It takes the original string, target length, padding string, and padding type (left, right, or both) as arguments.
📐

Syntax

The str_pad function has four parameters:

  • input: The original string you want to pad.
  • pad_length: The total length of the resulting string after padding.
  • pad_string (optional): The string used for padding. Defaults to a space.
  • pad_type (optional): Where to add the padding. Use STR_PAD_RIGHT (default), STR_PAD_LEFT, or STR_PAD_BOTH.
php
str_pad(string $input, int $pad_length, string $pad_string = " ", int $pad_type = STR_PAD_RIGHT): string
💻

Example

This example shows how to pad the string "cat" to length 7 using different padding types and characters.

php
<?php
// Original string
$word = "cat";

// Pad right with spaces (default)
echo str_pad($word, 7) . "\n";

// Pad left with dots
echo str_pad($word, 7, ".", STR_PAD_LEFT) . "\n";

// Pad both sides with dashes
echo str_pad($word, 7, "-", STR_PAD_BOTH) . "\n";
?>
Output
cat ....cat --cat--
⚠️

Common Pitfalls

Common mistakes include:

  • Setting pad_length shorter than the original string length, which returns the original string unchanged.
  • Using an empty string for pad_string, which causes a warning and no padding.
  • Forgetting to specify pad_type when you want padding on the left or both sides.
php
<?php
// Wrong: pad_length less than string length
echo str_pad("hello", 3, "*") . "\n"; // outputs 'hello'

// Wrong: empty pad_string
// echo str_pad("hi", 5, "") . "\n"; // Warning: pad_string cannot be empty

// Right: specify pad_type for left padding
echo str_pad("hi", 5, "*", STR_PAD_LEFT) . "\n";
?>
Output
hello ***hi
📊

Quick Reference

ParameterDescriptionDefault
inputThe string to padRequired
pad_lengthLength of the final stringRequired
pad_stringString used for paddingSpace (" ")
pad_typeWhere to pad: right, left, or bothSTR_PAD_RIGHT

Key Takeaways

Use str_pad to extend a string to a desired length by adding characters.
Specify pad_type to control padding direction: right, left, or both sides.
pad_string defaults to space but can be any string of characters.
If pad_length is less than the string length, the original string is returned.
Avoid empty pad_string to prevent warnings.