str_pad() extends a string to a target length using spaces or another padding string. Padding can be added on the right, left or both sides.
$label = 'PHP';
echo str_pad($label, 8, '.', STR_PAD_RIGHT); // PHP.....
echo str_pad("plus2net.com",15,"*");//output: plus2net.com***
echo str_pad("plus2net.com",15,"*",STR_PAD_LEFT);//output: ***plus2net.com
echo str_pad("plus2net.com",15,"*",STR_PAD_BOTH);//output: *plus2net.com**
Syntax
str_pad(string $string, int $length, string $pad_string = " ", int $pad_type = STR_PAD_RIGHT): string
| Parameters | DESCRIPTION |
|---|---|
$input_str | Required: Input string |
$length | Required : Target output length in bytes. If it is not greater than the input byte length, the original string is returned. |
$pad_string | Optional: Padding characters; a space is the default. An empty padding string is invalid. |
pad_type | Optional: Which side to pad. Options: STR_PAD_RIGHT ( default ) STR_PAD_LEFT STR_PAD_BOTH |
Padding is based on byte length, so Unicode characters can occupy more than one byte. For displaying columns in a webpage, prefer HTML tables or CSS layout.
Here is another example ofstr_pad():$sentence = "Welcome to Plus2net.com ASP Section to learn web programming";
foreach (explode(" ", $sentence) as $word) {
echo str_pad($word, 15, "-", STR_PAD_RIGHT) . "\n";
}
Author & Instructor at plus2net
I write and maintain practical tutorials on Python, PHP, SQL, JavaScript, HTML, jQuery, and web development at plus2net. The tutorials focus on clear explanations, working examples, and code that readers can test and adapt while learning.