str_pad() Padding strings on the left, right or both sides

Pad a string to a target length

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
ParametersDESCRIPTION
$input_strRequired: Input string
$lengthRequired : Target output length in bytes. If it is not greater than the input byte length, the original string is returned.
$pad_stringOptional: Padding characters; a space is the default. An empty padding string is invalid.
pad_typeOptional: Which side to pad. Options:
STR_PAD_RIGHT ( default )
STR_PAD_LEFT
STR_PAD_BOTH
Using the string function str_pad() we can pad one input string upto some given length or pad using another string. By default, the added characters are spaces on the right.

This function is useful when some data is to be formatted upto some length. We want the blank space after the input or marked with some chars like ---- . Another example is where we are displaying data in rows and wants all records to perfectly align in left and right. Here if all data are not of equal length we can pad them and keep all in one line. The extra space can be formatted as per requirement.

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 of str_pad():

Welcome--------
to-------------
Plus2net.com---
ASP------------
Section--------
to-------------
learn----------
web------------
programming----

The same word-by-word padding is generated by this example (line breaks shown as new lines):

$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";
}

explode() Break the string by using delimiter
String Functions Trim the string from both ends Change all alphabetic chars to Upper case Checking all lower case or upper case chars in a string


Subscribe to our YouTube Channel here



plus2net.com











PHP video Tutorials
✖
We use cookies to improve your browsing experience. . Learn more
HTML MySQL PHP JavaScript ASP Photoshop Articles Contact us
© 2000-2026 plus2net.com All rights reserved worldwide Privacy Policy Disclaimer