String Functions

PHP str_pad() Function

Topic: PHP String ReferencePrev|Next

Description

The str_pad() function pads a string to a certain length with another string.

The following table summarizes the technical details of this function.

Return Value: Returns the padded string.
Version: PHP 4.0.1+

Syntax

The basic syntax of the str_pad() function is given with:

str_pad(string, pad_length, pad_string, pad_type);

The following example shows the str_pad() function in action.

<?php
// Sample string
$str = "Hello World";

// Padding the string
echo str_pad($str, 16, "!");
?>

Parameters

The str_pad() function accepts the following parameters.

Parameter Description
string Required. Specifies the string to pad.
pad_length Required. Specifies the new length of the string. If its value is negative, less than, or equal to the length of the input string, no padding takes place.
pad_string Optional. Specifies the string to use for padding. Default is whitespace.
pad_type

Optional. Specifies which side to pad the string. Possible values are:

  • STR_PAD_RIGHT – Pad the string on the right side. Default value.
  • STR_PAD_LEFT – Pad the string on the left side.
  • STR_PAD_BOTH – Pad the string on both side. If the amount of padding cannot be evenly divided between each side, the right side gets the extra padding.

More Examples

Here're some more examples showing how str_pad() function actually works:

The following example demonstrates how to pad the left end of a string:

<?php
// Sample string
$str = "Hello World";

// Padding the left end of string
echo str_pad($str, 16, "*", STR_PAD_LEFT);
?>

The following example demonstrates how to pad both left and right end of a string:

<?php
// Sample string
$str = "Hello World";

// Padding both end of string
echo str_pad($str, 16, "*", STR_PAD_BOTH);
?>
Bootstrap UI Design Templates Property Marvels - A Leading Real Estate Portal for Premium Properties