Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP: Using str_pad not working? Why?

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!

like image 426
user1856596 Avatar asked Feb 04 '13 14:02

user1856596


People also ask

What is Str_pad function in PHP?

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.

Which of the following function pads one string with another in PHP?

The str_pad() function pads a string to a new length.


2 Answers

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;
like image 186
Ja͢ck Avatar answered Sep 25 '22 13:09

Ja͢ck


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.

like image 45
h2ooooooo Avatar answered Sep 25 '22 13:09

h2ooooooo