Python has a neat feature that does right alignment of strings with the syntax:
string.rjust(padding,fill_char)
> The method rjust() returns the string right justified in a string of length width. Padding is done using the specified fillchar (default is a space). The original string is returned if width is less than len(s).
Below you can find how to do it in PHP
##php rjust function
// by techblog.willshouse.com
function rjust($string,$total_length,$fillchar=’ ‘)
{
// if the string is longer than the total length allowed just return it
if(strlen($string) >= $total_length)
{
return $string;
}
$total_length = intval($total_length);
// total_length must be a number greater than 0
if( ! $total_length )
{
return $string;
}
// the $fillchar can’t be empty
if(!strlen($fillchar))
{
return $string;
}
// make the fill character into padding
while(strlen($fillchar) < $total_length)
{
$fillchar = $fillchar.$fillchar;
}
return substr($fillchar.$string, ( -1 * $total_length ));
}
### test php rjust function
header('Content-type: text/plain');
$items = array('one','a','superduper');
foreach($items as $item)
{
echo rjust($item,15);
echo "\n";
}
### php rjust function output
one
a
superduper
One Response to PHP rjust