This blog is NOFOLLOW Free!
  • INCEPTION THEME

    Clean, contrasting WordPress theme built on the foundation of Whiskey Air.
  • WHISKEY AIR THEME

    Clean developer theme, suited for heavy modifications.
  • X5 TURBO THEME

    3 columns Turbo theme, now reloaded!
  • CLEAR APPLE THEME

    Almost magazine theme, without the hassle of administration.
Quick Tip: PHP Number Padding

Recently I had to use PHP to display a score value such as “3″ padded as “03″. There’s a tiny PHP function that does just this.

1
2
$myvalue = '3';
str_pad((int) $myvalue,2,'0',STR_PAD_LEFT)

While working with strings, such as $myvalue, I had to convert it to integer using the (int) operator so I can make further calculations with my initial value.

The second parameter is the maximum number of characters to display, so if $myvalue is “10″, it will not be padded.

The third parameter is the character that will be padded, in my case “0″.

The fourth and last parameter is a PHP constant and it’s the position of the padding action, again in my case “left”.

That’s it.

If you wanted to right a function to deal with this, you would write the following:

1
2
3
function char_padding($value,$characters,$pad) {
return str_pad((int) $value,$characters,$pad,STR_PAD_LEFT);
}

and call it like this:

1
echo char_padding($myvalue,2,'0')

just make sure to have $myvalue already declared.

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=""> <strike> <strong>