Home »
PHP
PHP str_pad() function with example
By IncludeHelp Last updated : December 27, 2023
PHP str_pad() function
The str_pad() function is used to pad a string with whitespace (default) or any other character/string and returns the padded string.
Syntax
The syntax of the str_pad() function:
str_pad(source_string, length, [char/string], [padding_type]);
Parameters
The parameters of the str_pad() function:
- source_string - is the string to be padded.
- length - is the total number of characters of the targeted string after padding.
- char/string - to the padding character/string. It's an optional parameter, if we do not pass this parameter, string will be padded with whitespace.
-
padding_type - is the type of padding (it’s an optional parameter), it has following values:
- STR_PAD_LEFT - To pad the string from left side
- STR_PAD_RIGHT - To pad the string from right side
- STR_PAD_BOTH - To pad the string from both sides
Return Value
The return value of this method is string, it returns the string string padded on the left, the right, or both sides to the specified padding length. [Source]
Sample Input/Output
Input: 'Hello"
Function call: str_pad("Hello", 10, "*");
Output: "Hello*****"
Example of PHP str_pad() Function
<?php
$str = "Hello";
$padded_str = str_pad($str,10);
echo($padded_str."#\n");
$padded_str = str_pad($str,10,' ');
echo($padded_str."#\n");
$padded_str = str_pad($str,10,' ', STR_PAD_RIGHT);
echo($padded_str."#\n");
$padded_str = str_pad($str,10,' ', STR_PAD_LEFT);
echo($padded_str."#\n");
$padded_str = str_pad($str,10,' ', STR_PAD_BOTH);
echo($padded_str."#\n");
$padded_str = str_pad($str,10,'*', STR_PAD_BOTH);
echo($padded_str."#\n");
$padded_str = str_pad($str,10,'TEMP', STR_PAD_BOTH);
echo($padded_str."#\n");
?>
Output
The output of the above example is:
Hello #
Hello #
Hello #
Hello#
Hello #
**Hello***#
TEHelloTEM#
To understand the above example, you should have the basic knowledge of the following PHP topics: