勉強したことのメモ

Webエンジニア / プログラマが勉強したことのメモ

PHPでランダムな値を取得したいケース諸々の対応方法

   2024/04/18  PHP

テストデータを作成する際にランダムな値を入れたかったけど、色々ケースがあったので対応方法をメモ。

 

対応方法

範囲内のランダムな数値を取得

rand(0,10);

0から10の中からランダムな数値を取得できる。

配列からランダムにキーを取得

array_rand($array,1);

$arrayという配列から1つランダムにキーを取得できる。

重複せずにランダムな数値を配列に格納する

$array = range(1,10);
var_dump($array); //array(10) { [0]=> int(1) [1]=> int(2) [2]=> int(3) [3]=> int(4) [4]=> int(5) [5]=> int(6) [6]=> int(7) [7]=> int(8) [8]=> int(9) [9]=> int(10) }
shuffle($array);
var_dump($array); //array(10) { [0]=> int(1) [1]=> int(3) [2]=> int(5) [3]=> int(6) [4]=> int(8) [5]=> int(2) [6]=> int(10) [7]=> int(4) [8]=> int(9) [9]=> int(7) }

 

リファレンス

rand

https://www.php.net/manual/ja/function.rand.php

array_rand

https://www.php.net/manual/ja/function.array-rand.php

range

https://www.php.net/manual/ja/function.range.php

shuffle

https://www.php.net/manual/ja/function.shuffle.php

 - PHP

  関連記事

Stripeでキャンセル処理を行う際に「$config must be a string ~」エラーが出る場合の対応方法
Stripeでキャンセル処理を行う際に「$config must be a string ~」エラーが出る場合の対応方法

Stripeにて先日メモした内容でキャンセル(返金)処理をしようとしたところ1件 ...

PHPからCSVファイルを出力する際にメモリを節約する方法
PHPからCSVファイルを出力する際にメモリを節約する方法

MySQLよりデータを大量に取り出してCSVファイル化し、ダウンロードさせるとい ...

Codeigniter4でMySQLに接続しCRUD操作する方法
Codeigniter4でMySQLに接続しCRUD操作する方法

Codeigniter4.4.4でMySQLに接続しCRUD操作したい。また、任 ...

PHPで指定したディレクトリ内のファイルを全てincludeする方法
PHPで指定したディレクトリ内のファイルを全てincludeする方法

PHPでライブラリを利用する際にcomposerからインストールしたものは「ve ...

PHPで「operator not supported for strings」エラーの対応方法
PHPで「operator not supported for strings」エラーの対応方法

PHPにて「Fatal error: [] operator not suppo ...