SQL PHP HTML ASP JavaScript articles and free scripts to download
PHP String Functions

String str_pad function

Using the string function str_pad we can pad one input string upto some given length or pad using another string. If no second string is given then the input string is padded by blank space. We can even specify which side of the string the padding is to be done. Let us first see the syntax of str_pad function

str_pad ( input_string, length, pad_string, pad_type)

The last two arguments are optional. If the length specified is less than the input string length the input string is returned. If pad_type is returned then accordingly the string is padded at left, right or both sides. The pad_type can have values like

STR_PAD_LEFT
STR_PAD_RIGHT or
STR_PAD_BOTH

By default it is set to STR_PAD_RIGHT.
Let us try some examples

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**

This function is useful when some data is to be formatted upto some length. We want the blank space after the input is to be blanked 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.

Here is another example of str_pad function

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

The code for the above is here

$str="Welcome to Plus2net.com ASP Section to learn web programing";
$ar=split(" ",$str);
while (list ($key, $val) = each ($ar)) {
echo str_pad($val,15,"-",STR_PAD_RIGHT);
echo "<br>";
}

Be the first to post comment on this article :


Google+
Post Comment This is for short comments only. Use the forum for more discussions.
Name
Email( not to be displayed)Privacy Policy
1+2=This is to prevent automatic submission by spammers. Please enter the result of the sum as asked



Join Our Email List
Email:  
For Email Newsletters you can trust
HTML . MySQL. PHP. JavaScript. ASP. Photoshop. Articles. FORUM Contact us

©2000-2014 plus2net.com All rights reserved worldwide Privacy Policy Disclaimer