PHP str_pad() Function: Syntax, Parameters, Return Value, and Usage Examples
This article explains the PHP str_pad() function, detailing its syntax, parameters, return value, and demonstrating practical examples such as string padding, alignment, truncation, and numeric formatting to help developers efficiently manipulate string lengths.
The str_pad() function in PHP pads a string to a specified length by adding characters to the left, right, or both sides.
Function Syntax
<code>str_pad(string $input, int $pad_length, string $pad_string [, int $pad_type = STR_PAD_RIGHT]): string</code>Parameters
$input : the string to be padded.
$pad_length : the desired length after padding.
$pad_string : the character(s) used for padding.
$pad_type : optional, one of STR_PAD_LEFT , STR_PAD_RIGHT , or STR_PAD_BOTH ; default is STR_PAD_RIGHT .
Return Value
Returns the padded string.
Basic Example
<code>$input = "Hello";
$pad_length = 10;
$pad_string = "-";
$pad_type = STR_PAD_LEFT;
$result = str_pad($input, $pad_length, $pad_string, $pad_type);
echo $result; // -----Hello</code>Advanced Uses
1. String Alignment
<code>$text = "Hello";
$length = 10;
$pad_string = " ";
$leftAligned = str_pad($text, $length, $pad_string, STR_PAD_RIGHT);
$rightAligned = str_pad($text, $length, $pad_string, STR_PAD_LEFT);
$centerAligned = str_pad($text, $length, $pad_string, STR_PAD_BOTH);
echo $leftAligned . "\n";
echo $rightAligned . "\n";
echo $centerAligned . "\n"; // Outputs: "Hello \n Hello\n Hello "
</code>2. String Truncation
<code>$text = "Hello World";
$length = 10;
$pad_string = " ";
$paddedText = str_pad($text, $length, $pad_string);
$truncatedText = substr($paddedText, 0, $length);
echo $truncatedText; // Hello Worl
</code>3. Numeric Formatting
<code>$number = "123";
$length = 6;
$pad_string = "0";
$formattedNumber = str_pad($number, $length, $pad_string, STR_PAD_LEFT);
echo $formattedNumber; // 000123
</code>Summary
The str_pad() function is a versatile tool for controlling string length and formatting in PHP, supporting basic padding, alignment, truncation, and numeric zero‑padding, thereby enhancing string manipulation flexibility for backend development.
php中文网 Courses
php中文网's platform for the latest courses and technical articles, helping PHP learners advance quickly.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.