str_pad
Эта функция возвращает строку input , дополненную слева, справа или с обоих сторон до заданной длины. Если необязательный аргумент pad_string не передан, то input будет дополнен пробелами, иначе он будет дополнен символами из pad_string до нужной длины
Список параметров
Если значение pad_length отрицательно, меньше или равно длине входной строки, то дополнения не происходит.
Замечание:
pad_string может быть урезана, если необходимое количество дополняемых символов не делится нацело на длину строки pad_string .
Необязательный аргумент pad_type может иметь значение STR_PAD_RIGHT , STR_PAD_LEFT или STR_PAD_BOTH . Если не указан, то по умолчанию используется STR_PAD_RIGHT .
Возвращаемые значения
Возвращает дополненную строку.
Примеры
Пример #1 Пример использования str_pad()
$input = «Alien» ;
echo str_pad ( $input , 10 ); // выводит «Alien »
echo str_pad ( $input , 10 , «- color: #007700″>, STR_PAD_LEFT ); // выводит «-=-=-Alien»
echo str_pad ( $input , 10 , «_» , STR_PAD_BOTH ); // выводит «__Alien___»
echo str_pad ( $input , 6 , «___» ); // выводит «Alien_»
?>?php
PHP string str_pad() Function
The str_pad() is in-built PHP function which is use to pad a string to a certain length. It returns input string padded on the left, right both sides to the specified function.
Syntax:
- STR_PAD_BOTH
- STR_PAD_LEFT
- STR_PAD_RIGHT
Note 1: The pad-string may be reduced if the padding character can’t be divided by the pad_string’s length.
Note 2: If the pad_type is not specified then it assumed as STR_PAD_RIGHT.
Example 1
Output:
Your string isHello Javatpoint By using str_pad() function;Hello Javatpoint.
Example 2
Output:
Your string is:Javatpoint By using str_pad() function:Javatpoint
Example 3
Output:
Your string isHello Javatpoint By using str_pad() function. Hello Javatpoint
Example 4
Output:
Your string is: Javatpoint By using str_pad() function: Javatpoint.
Example 5
Output:
Your string isHello Javatpoint By using str_pad() function. Hello Javatpoint..
Next Topic PHP String

For Videos Join Our Youtube Channel: Join Now
Feedback
- Send your Feedback to [email protected]
Help Others, Please Share

Learn Latest Tutorials
![]()
![]()
![]()
![]()
![]()
![]()
![]()
![]()
![]()
![]()
![]()
![]()
Python Design Patterns
![]()
![]()
![]()
Preparation




Trending Technologies
![]()
![]()
![]()
![]()
![]()
![]()
![]()
![]()
![]()
![]()
![]()
![]()
B.Tech / MCA
![]()
![]()
![]()
![]()
![]()
![]()
![]()
![]()
![]()
![]()
![]()
![]()
![]()
![]()
![]()
![]()
![]()
![]()
![]()
![]()
![]()
![]()
![]()
Javatpoint Services
JavaTpoint offers too many high quality services. Mail us on h[email protected], to get more information about given services.
- Website Designing
- Website Development
- Java Development
- PHP Development
- WordPress
- Graphic Designing
- Logo
- Digital Marketing
- On Page and Off Page SEO
- PPC
- Content Development
- Corporate Training
- Classroom and Online Training
- Data Entry
Training For College Campus
JavaTpoint offers college campus training on Core Java, Advance Java, .Net, Android, Hadoop, PHP, Web Technology and Python. Please mail your requirement at [email protected].
Duration: 1 week to 2 week
Like/Subscribe us for latest updates or newsletter

str_pad() function in PHP
The str_pad() function is used to pad a string to a new length. It returns the padded string.
Syntax
str_pad(str, len, pad_str, pad_type)
Parameters
- str − The string to pad
- len − The new string length
- pad_str − The string to use for padding
- pad_type − The side to pad the string.
- The following are the possible values −
- STR_PAD_BOTH − Pad to both sides of the string. If not an even number, the right side gets the extra padding
- STR_PAD_LEFT − Pad to the left side of the string
- STR_PAD_RIGHT − Pad to the right side of the string.
Return
The str_pad() function returns the padded string.
Example
The following is an example −
Output
$$$Welcome
Example
The following is an example −
Output
Welcome$$$
Example
The following is an example −
PHP String Padding
In the previous chapter, we saw the basics of strings in PHP, such as the two special ways to denote string literals: heredoc and nowdoc; the mutability of strings, and even about string interpolation.
Another important aspect of strings in nearly all languages is that of padding, which we shall explore in this chapter. We’ll see how to left-align, right-align and center-align text when being output via the function str_pad() , in addition to configuring the fill character used in the padding.
Let’s dive right in.
What is padding?
Back in time when computers were still new in this enormous field of technology, we didn’t have such sophisticated graphical-processing units as we have today. Operating systems didn’t have graphical user interfaces as is mainstream these days.
What people largely had back then were mere textual interfaces. They’re even used to date, powering some of the more complicated set of commands on a computer machine, and commonly referred to as terminals, shells, CLIs (for Command Line Interfaces), etc.
These textual interfaces solely relied on text. Likewise, at times when precisely-formatted text was required such as a table, it became obvious to devise some simple technique to format the text.
One simple way was to use padding.
Padding is simply to extend the length of a string to a given length with a particular fill character.
For example, given the string ‘Hello’ , padding it to a length of 10 with the fill character — on the left side would produce the string ‘——Hello’ . The length of this padded string is 10.
String padding is extremely useful when tabular data ought to be output only using text. The data of each column is padded to a particular length, which gives a nice alignment to it. Altogether, the data seems to be nicely grouped and equally spaced with the help of padding.
The str_pad() function
In PHP, there is one and only one way to pad a string and that is str_pad() .
At most, the function can accept four arguments. This can be seen in the syntax below:
str_pad($string, $length[, $fill[, $pad_type]])Here’s what each argument does:
- $string is the main string that we wish to pad.
- $length is the length of the final padded string.
- $fill is the string that is used to pad $string to the desired length. It might be truncated in order to fit the given $length constraint. If omitted, it defaults to ‘ ‘ , i.e. the space character.
- $pad_type specifies the position where the padding is done in the string. Possible values are the constants STR_PAD_LEFT , STR_PAD_RIGHT and STR_PAD_BOTH . If omitted, defaults to STR_PAD_RIGHT .
We’ll explore all these $pad_type s later below.
For now, let’s consider a very quick example.
In the code below, we pad the string ‘Hello World!’ to a length of 20 with the fill character — :
Hello World!———
If we omit the $fill argument here, the space character would be used as the default fill character, as demonstrated below:
Hello World!
However, as you might agree, with the default setup, it’s quite difficult to visualize the space padding applied at the end of the text. One quick and easy way to visualize that is to output a character after the padded string.
This is done as follows:
Hello World! |
Amazing. Now, with the help of | , we can easily see the extra space at the end of $padded_str .
Note that if the given $length argument is less than or equal to the length of $string , the string is returned as it is. This is simply because there is no point of padding since the string has already occupied the given $length .
The code below illustrates this idea:
Hello World!
The string $str has a length of 12, while the desired length passed to str_pad() is just 5 . Likewise, ‘Hello World!’ is returned as it is by the call str_pad($str, 5) .
With the function str_pad() introduced, it’s time to consider each of the $pad_type values, i.e. STR_PAD_RIGHT , STR_PAD_LEFT and STR_PAD_BOTH .
Padding to the right
We’ll start with the default $pad_type value, that is STR_PAD_RIGHT .
As the name suggests, when $pad_type is set to STR_PAD_RIGHT , all the padding is applied on the right side of the given string.
For instance, consider the same snippet that we saw above:
Hello World!———
With the fill character as — , the padding is applied on the right side of $str to give the final padded string $padded_str .
Since STR_PAD_RIGHT is the default $pad_type , we have omitted it from the code snippet above. Whether we write str_pad($str, 20, ‘-‘) or str_pad($str, 20, ‘-‘, STR_PAD_RIGHT) , it’s exactly the same thing.
One very important point to remember is that STR_PAD_RIGHT effectively aligns the text of the given string to the left side, as the padding is applied on the right side.
Hence, if we want to left-align the actual text, we ought to use STR_PAD_RIGHT .
Padding to the left
The second $pad_type value is STR_PAD_LEFT .
In this type, all the padding is applied on the left side of the given string.
As the padding gets applied on the left side, the text moves to the right side. Hence, we can say that STR_PAD_LEFT effectively right-aligns a piece of text.
Consider the following code. Everything is the same as before except for that the $pad_type is set to STR_PAD_LEFT :
———Hello World!
Notice how the text is shifted to the right side.
STR_PAD_LEFT can also be visualized using space as the fill character, without the need to make any additional output as needed with STR_PAD_LEFT .
This can be seen as follows:
Hello World!
Padding on both sides
The third and last value of $pad_type is STR_PAD_BOTH .
It adds the padding to both sides of the given string until the desired length is reached.
As the padding is applied on both sides, the text shifts to the center. This means that STR_PAD_BOTH effectively center-aligns a given piece of text.
Consider the following code:
—-Hello World!—-
Note that if the padding on both sides of the given string can’t be made equal, then the right side gets the larger padding.
For instance, padding ‘A’ to a length of 6 with the fill character — , on both sides, will give the string ‘—A—‘ . The right side has 3 — characters while the left one has 2.
