str_pad()
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:
The PHP syntax of the str_pad()
string str_pad ( string $input , int $pad_length [, string $pad_string = " " [, int $pad_type = STR_PAD_RIGHT ]] )The function takes two required parameters: $input and $pad_length. $input is the string to pad, $pad_length is the length of the final padded string. It also accepts two optional parameters: $pad_string (defaults to a single space " ") and $pad_type, which specifies where to add padding. $pad_type can be STR_PAD_LEFT, STR_PAD_RIGHT, or STR_PAD_BOTH.
Here is an example of how to use the str_pad() function:
Example of PHP str_pad()
<?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:
00000HelloAs 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.
Note that if $pad_length is less than or equal to the length of $input, no padding is applied and the original string is returned. When using STR_PAD_BOTH, if the total padding difference is odd, the extra character is added to the right side.
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
What does the PHP str_pad() function do?