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.
$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:
function char_padding($value,$characters,$pad) { return str_pad((int) $value,$characters,$pad,STR_PAD_LEFT); }
and call it like this:
echo char_padding($myvalue,2,'0')
just make sure to have $myvalue already declared.