note 121699 deleted from function.array-rand by cmb

From: Date: Mon, 19 Oct 2020 06:37:42 +0000
Subject: note 121699 deleted from function.array-rand by cmb
References: 1  Groups: php.notes 
Request: Send a blank email to php-notes+get-215614@lists.php.net to get a copy of this message
Note Submitter: notmuqsit at gmail dot com ---- When the second argument is greater than 1, the output array will be arranged in ascending order. $a = ["Albert", "James", "Steve", "Charlie", "Sarah"]; The least value of array keys of $a is 0 and the highest is 4 in this case. Now let's do some tests. <?php //Infinite loops (never ending loops) while(array_rand($a, 2)[0] !== 4); while(array_rand($a, 2)[1] !== 0); //Non-infinite loops. while(array_rand($a, 2)[0] === 0); while(array_rand($a, 2)[1] === 4); ?> Why is this important? You will never get a perfectly random key if you aren't aware of that. array_rand($a, 2)[0] will NEVER return the last key (by the last key I mean the last key of the array when you arrange the array keys in ascending order). array_rand($a, 2)[1] will NEVER return the first key (by the first key I mean the first key of the array when you arrange the array keys in ascending order). In our case, <?php $random = array_rand($a, 2); echo $a[$random[0]];//Possible output: "Albert", "James", "Steve" or "Charlie" echo $a[$random[1]];//Possible output: "James", "Steve", "Charlie" or "Sarah" ?> You might want to shuffle($random) in such a case. This is only needed IF you have defined the second parameter and the second parameter > 1.

« previous php.notes (#215614) next »