Jacques
Jacques

Reputation: 117

PHP - Add leading zeros to number but keep maximum length

I have an Auto-Increment field in a database.

I want these numbers to be prepended by zeros, to a maximum length of seven.

Example:

Original number: 1 Desired result: 0000001

or

Original number 768 Desired result 0000768

How would I achieve this in PHP?

Upvotes: 5

Views: 7968

Answers (2)

B. Desai
B. Desai

Reputation: 16436

Use str_pad function of PHP

$input = 1;
$number = str_pad($input, 7, "0", STR_PAD_LEFT);

Upvotes: 8

colburton
colburton

Reputation: 4715

sprintf has this build in:

$number = sprintf("%07d", $input)

Upvotes: 2

Related Questions