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
str_pad(string $input, int $pad_length, string $pad_string [, int $pad_type = STR_PAD_RIGHT]): stringParameters
$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
$input = "Hello";
$pad_length = 10;
$pad_string = "-";
$pad_type = STR_PAD_LEFT;
$result = str_pad($input, $pad_length, $pad_string, $pad_type);
echo $result; // -----HelloAdvanced Uses
1. String Alignment
$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 . "
";
echo $rightAligned . "
";
echo $centerAligned . "
"; // Outputs: "Hello
Hello
Hello "2. String Truncation
$text = "Hello World";
$length = 10;
$pad_string = " ";
$paddedText = str_pad($text, $length, $pad_string);
$truncatedText = substr($paddedText, 0, $length);
echo $truncatedText; // Hello Worl3. Numeric Formatting
$number = "123";
$length = 6;
$pad_string = "0";
$formattedNumber = str_pad($number, $length, $pad_string, STR_PAD_LEFT);
echo $formattedNumber; // 000123Summary
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.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
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.
