Lesson 37 of 100
Strings15 min5 checksPHP 8.5

Pad and Repeat Strings

Use str_pad() to build fixed-width ASCII labels, choose which side receives the padding, and understand what happens when the text is already long enough.

01 · THE IDEAREAD → TRY → LEARN

Why pad strings?

Text output often needs columns: a name followed by dots, a number with leading zeros, or a title centered in a banner. str_pad() handles these cases without a manual loop. It takes a string and a target length, then adds characters until the string reaches that length.

The PHP 8.4 signature is str_pad(string $string, int $length, string $pad_string = " ", int $pad_type = STR_PAD_RIGHT): string. It always returns a new string. The original value is never modified.

The four arguments

  • $string is the text to extend.
  • $length is the desired final length, not the number of characters to add.
  • $pad_string supplies the filler. The default is a single space.
  • $pad_type chooses the side: STR_PAD_RIGHT (the default), STR_PAD_LEFT, or STR_PAD_BOTH.

The naming of the constants matters. STR_PAD_RIGHT puts padding on the right, so the original text stays on the left. A label that is "left aligned" therefore uses STR_PAD_RIGHT. Mixing these up is the most common mistake with this function.

A first look

The example below shows left padding with a two-character filler, centered padding, and a filler that must be cut off to fit.

Example
<?php
$input = "Alien";
echo str_pad($input, 10, "-=", STR_PAD_LEFT), PHP_EOL;
echo str_pad($input, 10, "_", STR_PAD_BOTH), PHP_EOL;
echo str_pad($input, 6, "___"), PHP_EOL;
Output
-=-=-Alien
__Alien___
Alien_

With STR_PAD_BOTH, five padding characters are needed. They cannot be split evenly, so the right side gets the extra one. A multi-character filler is repeated and cut off when it does not fit exactly.

No padding and no truncation

If $length is less than or equal to the current length, or is negative, you get the original string back. str_pad() never shortens text. If a column must have a strict maximum, you need a separate step such as substr() before padding.

The length is measured in bytes. For plain ASCII this equals the number of characters. Multibyte text is a different topic, and this lesson stays with ASCII labels.

An empty $pad_string or an invalid $pad_type raises a ValueError, so do not pass those values from untrusted input without checking them.

Building a small table

Padding is most useful when several lines must line up. Names are padded on the right with dots, and quantities are padded on the left with spaces so the digits line up.

Example
<?php
$items = ["Tea" => 3, "Coffee" => 12, "Milk" => 5];
foreach ($items as $name => $qty) {
    echo str_pad($name, 8, ".") . str_pad((string) $qty, 3, " ", STR_PAD_LEFT), PHP_EOL;
}
Output
Tea.....  3
Coffee.. 12
Milk....  5

str_pad() expects a string, so the integer quantity is cast first. Otherwise, a file without strict types would coerce it silently, and one with strict types would raise a TypeError.

Edge cases in one place

The next example gathers several behaviors into a JSON array: a target that is too small, a negative target, zero-padding for a number, a repeated line with str_repeat(), and an uneven centered pad.

Example
<?php
$result = [
    str_pad("abc", 2),
    str_pad("abc", -1, "*"),
    str_pad("7", 3, "0", STR_PAD_LEFT),
    str_repeat("=", 5),
    str_pad("ab", 7, "xyz", STR_PAD_BOTH),
];
echo json_encode($result, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES), PHP_EOL;
Output
["abc","abc","007","=====","xyabxyz"]

Notice the last value. Five characters are added, two on the left (xy) and three on the right (xyz). When padding is uneven, the right side is always the larger one.

Common mistakes

  1. Thinking $length is the amount of padding to add.
  2. Reversing the meaning of STR_PAD_LEFT and STR_PAD_RIGHT.
  3. Expecting long text to be cut down to $length.
  4. Forgetting that centered padding favors the right side.
  5. Passing an empty filler string.

Exercise contract

Write a function padLabel(string $label, int $width, string $align): string. It must pad the label with . characters to exactly $width bytes when the label is shorter than that. The alignment rules are:

  • "left" keeps the text on the left, so the dots go on the right.
  • "right" keeps the text on the right, so the dots go on the left.
  • "center" splits the dots, with any extra dot going on the right.
  • Any other alignment value behaves like "left".

If the label is already as wide as $width or wider, return it unchanged. The tests check the returned string, so do not echo anything. A match expression that converts the alignment name into a STR_PAD_* constant keeps the function short and easy to read.

Recap

str_pad() extends a string to a target length using a filler and a side. It never truncates, it measures bytes, and STR_PAD_RIGHT means the text stays on the left. Use str_repeat() when you need a plain run of one string, such as a divider line.

Before you start

Functions · Arrays · Types

You’ll practice
  • Build fixed-width ASCII labels
  • Implement and test a deterministic PHP 8.4 function
Your task

Make padLabel() pass all 5 checks. Run your code as often as you like, then check your answer.

exercise.phpSaved in this browserPHP 8.5
CONSOLE & CHECKS● Ready

Ready when you are

Your output will appear here.
Make it work. Then make it pass.

PHP loads on your first run. Each check starts fresh. Your code stays in this browser; clearing site data removes your progress. A check or the task looks wrong? Report a problem with this exercise.