LoginSignup
0
0

More than 3 years have passed since last update.

PHPで指定桁数の最大値を取得する

Last updated at Posted at 2020-07-29

もっとスマートな書き方がある気がしているので、ご教示いただきたいです。
→ (2020/07/30) コメント頂いたので、追記させていただきました!

指定桁数の最大値を取得

  • ※ 整数のみ対応
  • PHP_INT_MAXを超える桁数を$lengthに指定しないこと!

A1: str_repeat()を使う

$length = 6; // 6桁
$max = (int)str_repeat(9, $length); // 999999

A2: 累乗する

@vf8974 さんからコメント頂きました。確かにこちらの方が考え方がスマートです。

$max = 10 ** $length - 1;

注意点

当たり前なんですが、桁数$lengthに100など大きい桁を入れるとオーバーフローしますので、PHP_INT_MAX を超えない桁を指定して下さい。
https://www.php.net/manual/ja/language.types.integer.php#language.types.integer.overflow

integer型の範囲外の数を指定した場合、かわりに floatとして解釈されます。また、結果が integer型の範囲外の数となるような計算を行> うと floatが代わりに返されます。

もしそれより大きい桁が欲しいときは、string型で取得するしかありません。

$length = 30; // 30桁
$max = str_repeat(9, $length); // string(30) "999999999999999999999999999999"

(応用) 指定桁数までのランダムな整数値を取得

$rand_int = random_int(1, $max);
0
0
2

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
0
0