Today I got a situation where I need automatically zero filled number. I realized it could be done much str_pad
. The reason I am writing this post is, I just want to share with my readers.
str_pad — Pad a string to a certain length with another string. String pad is used to make a given string larger by N number of characters by adding specified string for padding , default is white space.
str_pad ( string $input, int $pad_length [, string $pad_string = " "[, int $pad_type = STR_PAD_RIGHT ]] )
$pad_types = STR_PAD_LEFT
, STR_PAD_RIGHT
, STR_PAD_BOTH
Following are the notes –
- If pad_type is not specified it is assumed to be STR_PAD_RIGHT.
- If not an even number, the right side gets the extra padding.
- If the optional argument pad_string is not supplied, the input is padded with spaces
- Specifies the pad_string length. If this value is less than the original length of the string, nothing will be happened.
Examples :
$string = "hello php"; // string lenth is 12 so pad_string value must be pad_string > 12 echo str_pad($string, 12,'a'); // outPut : hello phpaaa echo str_pad($string, 12,'a', STR_PAD_LEFT); // outPut : aaahello php echo str_pad($string, 12,'a', STR_PAD_RIGHT); // outPut : hello phpaaa echo str_pad($string, 13,'a', STR_PAD_BOTH); // outPut : aahello phpaa // NOTE : If not an even number, the right side gets the extra padding
Simple Function to get Zero Padded Numbers
function getZeroPaddedNumber($value, $padding, ,$pad_type = STR_PAD_LEFT) { return str_pad($value, $padding, "0", STR_PAD_LEFT); } echo getZeroPaddedNumber(123, 4); // outputs "0123"