PHP String Padding

Chapter 18 11 mins

Learning outcomes:

  1. What is padding
  2. The str_pad() function
  3. Padding to the right via STR_PAD_RIGHT
  4. Padding to the left via STR_PAD_LEFT
  5. Padding on both sides via STR_PAD_BOTH


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.

At its core,

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:

  1. $string is the main string that we wish to pad.
  2. $length is the length of the final padded string.
  3. $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.
  4. $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_types 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 -:


$str = 'Hello World!';
$padded_str = str_pad($str, 20, '-');

echo $padded_str;
Hello World!--------

If we omit the $fill argument here, the space character would be used as the default fill character, as demonstrated below:


$str = 'Hello World!';
$padded_str = str_pad($str, 20);

echo $padded_str;
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:


$str = 'Hello World!';
$padded_str = str_pad($str, 20);

echo $padded_str . '|';
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:


$str = 'Hello World!';
$padded_str = str_pad($str, 5);

echo $padded_str;
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:


$str = 'Hello World!';
$padded_str = str_pad($str, 20, '-');

echo $padded_str;
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:


$str = 'Hello World!';
$padded_str = str_pad($str, 20, '-', STR_PAD_LEFT);

echo $padded_str;
--------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:


$str = 'Hello World!';
$padded_str = str_pad($str, 20, ' ', STR_PAD_LEFT);

echo $padded_str;
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:


$str = 'Hello World!';
$padded_str = str_pad($str, 20, '-', STR_PAD_BOTH);

echo $padded_str;
----Hello World!----

Simple, isn't this?

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.

"I created Codeguage to save you from falling into the same learning conundrums that I fell into."

— Bilal Adnan, Founder of Codeguage