Our article is about the PHP function str_pad(), which is used to pad a string with another string until it reaches a specified length. This function is useful when you need to format strings to a specific length or add padding to strings. In this article, we will discuss the syntax and usage of str_pad(), as well as provide some examples.

The str_pad() function is used to pad a string with another string until it reaches a specified length. The syntax of the str_pad() function is as follows:

string str_pad ( string $input , int $pad_length [, string $pad_string = " " [, int $pad_type = STR_PAD_RIGHT ]] )

The function takes three required parameters: $input, $pad_length, and $pad_string. $input is the string to pad, $pad_length is the length of the final padded string, and $pad_string is the string to use for padding. The function also takes an optional parameter, $pad_type, which specifies where to add padding. It can be STR_PAD_LEFT, STR_PAD_RIGHT, or STR_PAD_BOTH.

Here is an example of how to use the str_pad() function:

<?php
$input = "Hello";
$pad_length = 10;
$pad_string = "0";
$pad_type = STR_PAD_LEFT;

$output = str_pad($input, $pad_length, $pad_string, $pad_type);
echo $output; // Output: 00000Hello
?>

In this example, we have a string variable $input that contains the word "Hello". We use the str_pad() function to add padding to the string until it reaches a length of 10 characters. We have also specified the padding string to be "0" and the padding type to be STR_PAD_LEFT. This means that the string will be padded with zeros on the left until it reaches a length of 10 characters.

The output of this code will be:

00000Hello

As you can see, the str_pad() function has successfully padded the string "Hello" with zeros on the left until it reached a length of 10 characters.

The str_pad() function is a useful tool for padding a string with another string until it reaches a specified length. It allows you to easily format strings to a specific length or add padding to strings in PHP. By mastering this function, you can become a more proficient PHP developer.

We hope this article has been helpful in understanding the str_pad() function in PHP.

Practice Your Knowledge

What does the PHP str_pad() function do?

Quiz Time: Test Your Skills!

Ready to challenge what you've learned? Dive into our interactive quizzes for a deeper understanding and a fun way to reinforce your knowledge.

Do you find this helpful?