I have a string, its content is "24896". Now I want to add some zeros to the left, so I tried:
$test = str_pad($myString, 4, "0", STR_PAD_LEFT);
The result is "24896" again, no zeros added to the left. Am I missing something here?
Thanks!
The str_pad() function is a built-in function in PHP and is used to pad a string to a given length. We can pad the input string by any other string up to a specified length. If we do not pass the other string to the str_pad() function then the input string will be padded by spaces.
The str_pad() function pads a string to a new length.
The second argument to str_pad()
takes the full length of the final string; because you're passing 4 and the length of $myString
is 5, nothing will happen.
You should choose a width that's at least one bigger than your example value, e.g.:
str_pad($myString, 9, '0', STR_PAD_LEFT);
// "000024896"
Update
This might be obvious, but if you always want 4 zeros in front of whatever $myString
is:
'0000' . $myString;
Because you're padding it to length 4, and your string 24896
is 5 characters long, hence it doesn't need to pad anything as it's already more than 4 characters long.
The second parameter in the str_pad
function is the new length of the string.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With