PHPでランダムな値を取得したいケース諸々の対応方法
2024/04/18
テストデータを作成する際にランダムな値を入れたかったけど、色々ケースがあったので対応方法をメモ。
目次
対応方法
範囲内のランダムな数値を取得
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
関連記事
-
-
PHPとajaxでチャットの作成
■ソース ・index.php <? error_reporting(E_ ...
-
-
PHPで日時比較時の注意
PHPで日時を比較する際にミスがあったのでメモ。 基本形は下記。 $limit_ ...
-
-
PHPでXML形式データをオブジェクト・JSON・連想配列に変換する方法
先日バニラJavaScriptでXML形式データの取り扱いとJSON形式への変換 ...
-
-
PHPでメルマガを配信する方法(1件ずつ送信するパターン)
以前にPHPでメルマガを配信する方法を書いたけど、BCCだと相手の名前などユーザ ...
-
-
PHPでファイル書き込み時に「failed to open stream: HTTP~~」エラー
PHPでファイルを書き込む際に「failed to open stream: H ...