Monday, 29 September 2014

str_pad in PHP

PHP str_pad() function is utilized to returns a string by padding a specified string to a new length.

Syntax:

str_pad(string,length,pad_string,pad_type)
string : Required. Defines the input string

length : Required. Defines  the new string length. If the padding length is negative, less or equal to input string nothing will be done.
pad_string : Optional. Defines the string to use for padding. Default is whitespace.

pad_type : Optional. Defines what side to pad the string.
Possible values :

STR_PAD_BOTH : Pad to both sides of the string. If not an even number, the right side gets the additional  padding
STR_PAD_LEFT : Pad to the left half of the string
STR_PAD_RIGHT : Pad to the right half of the string
Example:

<?php
$str_name = "Good Morning";
echo "Example with no pad_type parameter : <br />";
echo str_pad($str_name,18,".");
echo "Example with pad_type set to STR_PAD_LEFT : <br />";
echo str_pad($str_name,17,".",STR_PAD_LEFT);
echo "Example with pad_type set to STR_PAD_BOTH : <br />";
echo str_pad($str_name,17,".",STR_PAD_BOTH);
?>
Output will be:
Example with no pad_type parameter :
 Good Morning......
Example with pad_type set to STR_PAD_LEFT :
.....Good Morning
Example with pad_type set to STR_PAD_BOTH :
 ..Good Morning...

0 comments:

Post a Comment