English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

PHP Basic Tutorial

PHP Advanced Tutorial

PHP & MySQL

PHP Reference Manual

PHP str_pad() Function Usage and Example

    PHP String Character String Functions Manual

    The str_pad() function is used to pad a string to a specified length using another string.

Syntax

str_pad(string,length,pad_string,pad_type)

Definition and Usage

It is used to pad the string to a new length. The function returns the string after being padded from the left end, right end, or both ends to the specified length. If the optional pad_string parameter is not specified, the string will be filled with space characters, otherwise it will be filled with pad_string to the specified length.

Return Value

It returns the padded string

Parameter

Serial NumberParameters and Description
1

string

Required. It specifies the string to be padded

2

length

Required. It specifies the new string length

3

pad_string

Optional. It specifies the string used for padding

4

pad_type

Optional. Specify which side of the padding string.

Possible Values:

  • STR_PAD_BOTH - Pad the string on both sides. If the number is odd, the right side gets extra padding.

  • STR_PAD_LEFT - Pad the string on the left side.

  • STR_PAD_RIGHT - Pad the string on the right side. This is the default.

Online Example

Try the following example, using str_pad to pad strings:

<?php
   
   //Use: to pad the string on the right side
   $input = "w3
   echo str_pad($input,18,":"); 
   
   echo '<br>';
    //Pad the string on the left side
   $str = "w3
   echo str_pad($str,20,"!",STR_PAD_LEFT);
   
   echo '<br>';
    //Pad the string on both sides
   $str = "wwww.w3
   echo str_pad($str,20,"-",STR_PAD_BOTH);
?>
Test and see‹/›

Output Result

w3codebox::::::::::::
!!!!!!!!!!!oldtoolbag.com
---wwww.oldtoolbag.com---

PHP String Character String Functions Manual