note 120180 deleted from function.array-rand by cmb
| From: | cmb@php.net | Date: | Mon, 19 Oct 2020 06:37:33 +0000 |
| Subject: | note 120180 deleted from function.array-rand by cmb | ||
| References: | 1 | Groups: | php.notes |
| Request: | Send a blank email to php-notes+get-215613@lists.php.net to get a copy of this message | ||
Note Submitter: sondermann dot m at gmail dot com
----
It is not written on here but you should note that the keys that are returned are always sorted low
to high.
This was unexpected for me since my main reason to use this function was to get a random subset of
an array (use case was to list products in a sidebar).
As a result of this, even if the same products were picked randomly another time, they were always
arranged in the same way.
This is my solution, may help someone who also needs a fully randomized subset of an array:
<?php
function array_random_keys( $array, $num = 1 ) {
if ( !is_array( $array ) ) return $array;
if( (int)$num < 1 ) return array();
$keys = array_keys($array);
shuffle($keys);
if( $num == 1 ) {
return $keys[0];
}
return array_splice( $keys, 0, $num );
}
?>