Sam
Sam

Reputation:

Adding an echo with a string in PHP?

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 ?

Upvotes: 0

Views: 272

Answers (5)

Matt
Matt

Reputation: 2230

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.

Upvotes: 1

Mark
Mark

Reputation: 1376

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

Upvotes: 1

vartec
vartec

Reputation: 134581

printf("%06d", $id)

Upvotes: 2

karim79
karim79

Reputation: 342635

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

Upvotes: 6

user7094
user7094

Reputation:

You could check out str_pad

In your case it would be something like:

str_pad('1', 6, '0', STR_PAD_LEFT);

Upvotes: 7

Related Questions