PHP rjust

Python has a neat feature that does right alignment of strings with the syntax:


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


Related Posts:

  • No Related Posts
This entry was posted in Tech Tips, Web Development and tagged . Bookmark the permalink.

One Response to PHP rjust

  1. marco says:

    Please take a look at “str_pad” php function:


Leave a Reply

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