PHP’s str_pad()
function will pad a string to a certain length using another string.
The str_pad()
function does this padding by adding more characters from a set of characters indicated by the second parameter passed to it.
This addition will increase the length of the string in total to the length indicated by the third parameter passed to the function as well.
The basic syntax of the function:
str_pad(
$string,
$length,
$pad_string,
$pad_type
);
$string
: The string to be padded.$length
: An integer value that indicates the new length of the string after padding.Note: The
$length
parameter must be greater than the initial length of the string. If it is less than or equal to the string’s length or negative, there will be no padding on the string, and the string is returned as it is. This is a required parameter.
$pad_string
: The string used to do the padding. This parameter is optional. If it is not provided, the default value of empty string (""
) will be used.Note: If the length of the
$pad_string
provided cannot evenly divide the required number of padding characters, then thepad_string
will be truncated.
$pad_type
: This argument is optional. When it’s not provided, the default STR_PAD_RIGHT
value will be assumed. Other pad_type
includes STR_PAD_LEFT
and STR_PAD_BOTH
.This function returns the padded string.
Note: It is supported by PHP versions 4.0.1 and later.
<?php//the input value to be padded.$input = "Trick";//no padding characters, defaults to spaces$mani = str_pad($input, 10);echo $mani . "test" . "\n";// check if $mani was padded, echo new lengthecho strlen($mani). "\n";// add strings to the left.echo str_pad($input, 10, "-=", STR_PAD_LEFT)."\n";//add strings to both sidesecho str_pad($input, 10, "_", STR_PAD_BOTH). "\n";//no pad_type value, defaults to right paddingecho str_pad($input, 6, "___"). "\n";/*the pad_string length is lessthan the $input string lengthso no padding was done*/echo str_pad($input, 3, "*"). "\n";?>
In the code example above, the variable $trick1
is padded with different str_pad()
options, producing different outputs.
The default pad_type
is STR_PAD_RIGHT
, the required number of padding characters can’t be evenly divided when using STR_PAD_BOTH
. So the padding to the right will be favored over padding to the left.
Let’s see this with a simple code example:
<?phpecho str_pad("output", 11, "pp", STR_PAD_BOTH )."\n";echo str_pad("output", 7, "p", STR_PAD_BOTH )."\n";echo str_pad("output", 9, "p", STR_PAD_BOTH )."\n";?>