getButterfly Logo getButterfly code wrangling since 2005

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.

[php]$myvalue = ‘3’;
str_pad((int) $myvalue,2,’0′,STR_PAD_LEFT)[/php]

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:

function char_padding($value,$characters,$pad) {
return str_pad((int) $value,$characters,$pad,STR_PAD_LEFT);

and call it like this:

[php]echo char_padding($myvalue,2,’0′)[/php]

just make sure to have $myvalue already declared.

Subscribe to getButterfly Blog

Once a week or so we send an email with our best content. We never bug you, we just send you our latest piece of content.

If you found any value in this post, agree, disagree, or have anything to add - please do. I use comments as my #1 signal for what to write about. Read our comment policy before commenting! Comments such as "Thank you!", "Awesome!", "You're the man!" are either marked as spam or stripped from URL.

Leave a reply