Php function for Zero-pad digits in string

To zero-pad digits in a string, you can use the str_pad() function in PHP. The str_pad() function allows you to pad a string to a specified length with another string.

To zero-pad digits in a string, you can specify the length of the resulting string and use "0" as the padding string. For example, if you have the string "123" and you want to pad it with leading zeros to a length of 5 characters, you can use the following code:


$str = "123";
$pad_length = 5;
$padded_str = str_pad($str, $pad_length, "0", STR_PAD_LEFT);
echo $padded_str; // outputs "00123"

In this example, str_pad() is used to add leading zeros to the string "123". The $str variable is the string to be padded, $pad_length is the total length of the resulting string (including the original string and the padding), and "0" is the padding string (in this case, zero).

The fourth argument to str_pad() is the padding position. In this example, "STR_PAD_LEFT" is specified to add the padding to the left of the original string. If you want to add the padding to the right of the original string, you can use "STR_PAD_RIGHT".

Comments

Leave a Reply