Feb 07

Padding string without loops

So if we wanted to pad a string in PHP with a prefix or suffix generally we would need to do this

$baseStr = 'hello';
$pad = '-=-';
$added = '';
for($i = 0; $i < 5; $i++)
    $added .= $pad;
echo $added.$baseStr;

now obviously if we were adding a suffix we’d skip $added and just append the original string (if we didn’t want to keep it). however for shits and giggles say we didn’t want to use a loop, how do we do it then? well there’s str_pad

now yes it does pad a string to a specified length and if the source string is greater than this it wont add anything (as shown in the examples on php.net). there is where this function comes in

function padString($str,$padStr,$count,$prefix=false)
        $prefix = STR_PAD_LEFT;
        $prefix = STR_PAD_RIGHT;
    return str_pad($str,(strlen($str)+(strlen($padStr)*$count)),$padStr,$prefix);

accepting the soruce string, the padding string and how many times you want the padding string to be repeated we use str_pad to add it without a loop. this is done by calculating how long our string will be after this is done. for instance:

$str        = 'hello';    // length = 5
$padStr        = '=.';        // length = 2
$count        = 15;

the second argument does 5 + (2 x 15) which comes out to 35. so we know that our result will be a string 35 characters long and with this we have the values we need for str_pad.

the final argument of my function is just to set the final argument of str_pad which determines if this is going in front of behind the string

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>