note 120180 added to function.array-rand

From: Date: Thu, 17 Nov 2016 15:41:07 +0000
Subject: note 120180 added to function.array-rand
Groups: php.notes 
Request: Send a blank email to php-notes+get-207152@lists.php.net to get a copy of this message
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 ); } ?> ---- Server IP: 72.52.91.14 Probable Submitter: 178.12.135.106 ---- Manual Page -- http://php.net/manual/en/function.array-rand.php Edit -- https://master.php.net/note/edit/120180 Del: integrated -- https://master.php.net/note/delete/120180/integrated Del: useless -- https://master.php.net/note/delete/120180/useless Del: bad code -- https://master.php.net/note/delete/120180/bad+code Del: spam -- https://master.php.net/note/delete/120180/spam Del: non-english -- https://master.php.net/note/delete/120180/non-english Del: in docs -- https://master.php.net/note/delete/120180/in+docs Del: other reasons-- https://master.php.net/note/delete/120180 Reject -- https://master.php.net/note/reject/120180 Search -- https://master.php.net/manage/user-notes.php

« previous php.notes (#207152) next »