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:
The following example shows the str_pad() function in action.
Example
Run this code »<?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:
|
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:
Example
Run this code »<?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:
Example
Run this code »<?php
// Sample string
$str = "Hello World";
// Padding both end of string
echo str_pad($str, 16, "*", STR_PAD_BOTH);
?>

