In PHP 8.4 and PHP 8.5, the str_pad() function behaves exactly the same as in earlier versions. It pads a string to a specified length with another string, on the left, right, or both sides.
Syntax
The function signature is:
str_pad(string $string, int $length, string $pad_string = " ", int $pad_type = STR_PAD_RIGHT): string
- $string: The input string to pad.
- $length: The desired final length. If this value is less than or equal to the input string is length, no padding occurs and the original string is returned.
- $pad_string (Optional): The string used for padding. Defaults to a space (" ") if not provided.
- $pad_type (Optional): Which side to pad. Valid values are STR_PAD_RIGHT (default), STR_PAD_LEFT, or STR_PAD_BOTH.
Examples
- Here are some common use cases from the official documentation:
<?php
$input = "Alien";
// Default: pad with spaces on the right
echo str_pad($input, 10);
// Output: "Alien "// Pad on the left with "-=" pattern
echo str_pad($input, 10, "-=", STR_PAD_LEFT);
// Output: "-=-=-Alien"// Pad on both sides with "_"
echo str_pad($input, 10, "_", STR_PAD_BOTH);
// Output: "__Alien___"?>
Points (PHP 8.4/8.5)
- No Version-Specific Changes:
- There are no new features, deprecations, or behavior changes for this function in PHP 8.4 or 8.5. It remains stable as before.
- Not Multibyte-Safe:
- str_pad() does not handle multibyte characters (like Hindi or emoji) correctly, because it calculates length by treating each character as a single byte. For multibyte strings, you may need manual handling or a custom function.
- Truncation:
- If the number of padding characters needed is not evenly divisible by the length of $pad_string, the $pad_string may be truncated.
Let me know if you d like an example for a specific use case (like formatting numbers with leading zeros).