0

I have an echo = "000000" and a string named $id which is an integer.

If $id is = 1, how do I add "000000" + $id to get 000001 ?

1
  • apparently someone forgot what it was like to be new at something.... Commented Apr 1, 2009 at 19:09

5 Answers 5

7

You could check out str_pad

In your case it would be something like:

str_pad('1', 6, '0', STR_PAD_LEFT);
Sign up to request clarification or add additional context in comments.

Comments

6
function padWithZeros($s, $n) {
  return sprintf("%0" . $n . "d", $s);
}

Where $n is the number of zeros you want, e.g:

echo padWithZeros("1", 6);

That pads the number 1 with five zeros to equal six places

Comments

2
printf("%06d", $id)

Comments

1

$temp = "00000".$id; echo "ID = $temp";

Comments

1

str_pad is the PHP function that does exactly what you want. However, printf is a well understood method of doing that that works across most common languages. It probably makes sense to use printf in this case to make the code more readable.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.