← Back to Chapters

PHP str_pad() & str_repeat()

? PHP str_pad() & str_repeat()

? Quick Overview

PHP provides string padding and repeating functions like str_pad() and str_repeat() that allow you to modify strings by padding them with characters or repeating them multiple times. These functions are useful for formatting strings or creating fixed-length strings.

?️ Key Concepts

  • str_pad() – Pads a string to a fixed length.
  • str_repeat() – Repeats a string multiple times.

? Syntax & Theory

  • str_pad(string, length, pad_string, pad_type)
  • str_repeat(string, times)

? Code Example: str_pad()

? View Code Example
// Padding a string to fixed length using default right padding
<?php
$string = "PHP";
$padded = str_pad($string, 10, "*");
echo $padded;
?>

? Output

PHP******

? Code Example: Padding Direction

? View Code Example
// Demonstrating left, right, and both side padding
<?php
$string = "PHP";
echo str_pad($string, 10, "*", STR_PAD_LEFT);
echo str_pad($string, 10, "*", STR_PAD_RIGHT);
echo str_pad($string, 10, "*", STR_PAD_BOTH);
?>

? Output

*****PHP
PHP*****
**PHP****

? Code Example: str_repeat()

? View Code Example
// Repeating a string multiple times
<?php
$string = "PHP";
echo str_repeat($string, 3);
?>

? Output

PHPPHPPHP

? Interactive Visual Example

Padding visualization using blocks

*****PHP PHP***** **PHP****

? Use Cases

  • Formatting table columns
  • Generating fixed-width reports
  • Creating visual separators
  • Zero-padding numeric values

✅ Tips & Best Practices

  • Use str_pad() for clean aligned output
  • Prefer constants like STR_PAD_LEFT for clarity
  • Avoid excessive repetition for performance reasons
  • Pad numbers with zeros for IDs and invoice numbers

? Try It Yourself

  • Create a zero-padded invoice number
  • Generate a star separator using str_repeat()
  • Align names and scores using str_pad()