57 of 410 menu

The str_pad Function

The str_pad function pads a string to a specified length with another string. The first parameter takes the string, the second - the number of characters to which the string should be padded, the third parameter - what to pad the string with.

The fourth optional parameter specifies which side to pad the string from. This parameter can take the following values: STR_PAD_LEFT - pad the string from the left, STR_PAD_RIGHT - pad the string from the right (this is the default value).

Syntax

str_pad(string $string, int $length, string $pad_string = " ", int $pad_type = STR_PAD_RIGHT): string

Example

Let's pad the string with the character '+' so that the string becomes 10 characters long:

<?php $arr = 'abcde'; echo str_pad($arr, 10, '+'); ?>

Code execution result:

'abcde+++++'

Example

Now the string will be padded from the left, not from the right:

<?php $arr = 'abcde'; echo str_pad($arr, 10, '+', STR_PAD_LEFT); ?>

Code execution result:

'+++++abcde'

See Also

  • the array_pad function,
    which pads an array with specified elements
  • the array_fill function,
    which fills an array with a specified value
  • the str_repeat function,
    which repeats a string a specified number of times
byenru