20
17

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

PHPで数字を0埋めして桁を揃える

Posted at

うーーーん。。str_padよりsprintfの方が読みやすいかな。(他の言語でも標準的だし)

str_padを使う

$i = 1;
echo str_pad($i, 10, '0', STR_PAD_LEFT);
// 0000000001

第4引数をSTR_PAD_LEFTに指定すると、埋める場所が左側になるのでそれっぽい感じに。

sprintfを使う

%dに、0(0で桁埋めする)と10(桁にする)オプションを指定してフォーマットする。

$i = 1;
echo sprintf('%010d', $i);
// 0000000001
20
17
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
20
17

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?