0
0

More than 3 years have passed since last update.

PHPで配列をソート、シャッフルする

Posted at

学習記録

前提条件

・PHP version 5.4

配列のソートとシャッフル

・sort
・rsort
・shuffle
・array_rand

sort

配列の要素を小さい順に並べる

built.php
$scores = [40, 50, 20, 30];

sort($scores);
print_r($scores);
//結果: Array(
//             [0] => 20
//             [1] => 30
//             [2] => 40
//             [3] => 50)

rsort

配列の要素を大きい順に並べる

built.php
$scores = [40, 50, 20, 30];

rsort($scores);
print_r($scores);
//結果: Array(
//             [0] => 50
//             [1] => 40
//             [2] => 30
//             [3] => 20)

shuffle

配列の要素をシャッフルする

built.php
$scores = [20, 30, 40, 50];

shuffle($scores);
print_r($scores);
//結果: Array(
//             [0] => 40
//             [1] => 30
//             [2] => 50
//             [3] => 20)

array_rand

配列からランダムでいくつかのキーを抜き出して新しい配列をつくる

書式
array_rand(配列, 個数)
built.php
$scores = [40, 50, 20, 30];

$picked = array_rand($scores, 2);

echo $scores[$picked[0]] . PHP_EOL;
//結果 :  50
echo $scores[$picked[1]] . PHP_EOL;
//結果 :  30
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