PHP Function Reference

PHP str_pad() Function



The PHP str_pad() function returns the string padded on the left, the right, or both sides to the specified padding length. If the optional argument pad_string is not supplied, the string is padded with whitespaces, otherwise it is padded with characters from pad_string up to given length.

Syntax

str_pad(string, length, pad_string, pad_type)

Parameters

string Required. Specify the input string.
length Required. Specify the new string length. If it is negative, less than, or equal to the length of the string, no padding takes place, and string will be returned.
pad_string Optional. Specify the string to use for padding. Default is whitespace.
pad_type Optional. Specify which side to pad. Possible values are:
  • STR_PAD_RIGHT: Pad to the right side of the string.
  • STR_PAD_LEFT: Pad to the left side of the string.
  • STR_PAD_BOTH: Pad to both side of the string. If not an even number, the right side will get the extra padding.
Default is STR_PAD_RIGHT.

Return Value

Returns the padded string.

Example:

The example below shows the usage of str_pad() function.

<?php
$str = "Hello";

//returns: "Hello     "
echo str_pad($str, 10)."\n"; 

//returns: "-=-=-Hello"
echo str_pad($str, 10, "-=", STR_PAD_LEFT)."\n"; 

//returns: "__Hello___"
echo str_pad($str, 10, "_", STR_PAD_BOTH)."\n";

//returns: "Hello*"
echo str_pad($str, 7, "*")."\n";

//returns: "Hello"
echo str_pad($str, 3, "#")."\n";
?>

The output of the above code will be:

Hello     
-=-=-Hello
__Hello___
Hello**
Hello

❮ PHP String Reference