0
0

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 で 配列の値を順番までランダムにして取得する関数

Last updated at Posted at 2019-07-30

PHP で普通に配列から値を取得しようとすると array_rand() で取得したキーを元の配列に入れる微妙な面倒さがあり、ついでにこれだけだと順番がランダムになっていなくて、それもまた微妙に面倒。

ということで配列と取り出す数を指定してサクッとランダムに取り出せる関数を書いた

function array_rand_and_shuffle(array $array, int $num_req)
    {
        shuffle($array);
        // 配列の要素数が取得数に満たない場合はシャッフルだけする
        if(count($array) <= $num_req) return $array;

        $random_keys = array_rand($array, $num_req);
        $rand_array = [];
        foreach($random_keys as $key){
            $rand_array[] = $array[$key];
        }
        return $rand_array;
    }
0
0
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
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?