PHP Tutorial - PHP str_pad() Function






Definition

The str_pad() function makes a given input larger by length.

Syntax

PHP str_pad() Function has the following syntax.

string str_pad ( string input, int length [, string padding [, int type]] )

Parameter

ParameterIs RequiredDescription
stringRequired.String to pad
lengthRequired.New string length. If this value is less than the original length of the string, nothing will be done
pad_stringOptional.String to use for padding. Default is whitespace
pad_typeOptional.What side to pad the string.

Possible values for pad_type:

  • STR_PAD_BOTH - Pad to both sides of the string. If not an even number, the right side gets the extra padding
  • STR_PAD_LEFT - Pad to the left side
  • STR_PAD_RIGHT - Pad to the right side. This is default




Return

PHP str_pad() function returns the padded string.

Example 1

Padding on both side


<?PHP
$string = " java2s.com "; 
$newstring = str_pad($string, 30); 
print ">"+$newstring+"<";
?>

The code above generates the following result.

Example 2

An optional third parameter sets the padding character to use, so:


<?PHP
$string = " java2s.com!"; 
$newstring = str_pad($string, 20, 'a'); 
print $newstring;
?>

The code above generates the following result.





Example 3

The optional fourth parameter specifies which side we want the padding added to. The fourth parameter can be either STR_PAD_LEFT, STR_PAD_RIGHT, or STR_PAD_BOTH:


<?PHP/* ww  w  . j  a  va2s .  co  m*/
$string = " java2s.com!"; 
$a = str_pad($string, 20, '-', STR_PAD_LEFT); 
print $a;
print "\n";
$b = str_pad($string, 20, '-', STR_PAD_RIGHT); 
print $b;
print "\n";
$c = str_pad($string, 20, '-', STR_PAD_BOTH); 
print $c;
?>

To pad more spaces to HTML, you will need to use &nbsp; the HTML code for a non-breaking space.

The code above generates the following result.