4
5

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】配列から指定したエントリの数のバリューをランダムに抽出する

Posted at

前書き

既知のメソッドがあるかなーと思ったらなかったので、作りました。

code

array_rand_value.php
/**
 * 配列から指定したエントリの数のバリューをランダムに抽出する
 * 
 * @param array $array 抽出元の配列
 * @param int $num 取得する要素数
 * @return array 抽出後の配列
 */
function array_rand_value($arr, $num = 1)
{
	if ($num >= count($arr)) {
		return $arr;
	}

	$result = array();
	$rand_keys = array_rand($arr, $num);
	foreach ($rand_keys as $key) {
		$result[] = $arr[$key];
	}

	return $result;
}
4
5
13

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
4
5

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?