note 115731 added to function.array-rand

From: Date: Sun, 14 Sep 2014 03:31:10 +0000
Subject: note 115731 added to function.array-rand
Groups: php.notes 
Request: Send a blank email to php-notes+get-200442@lists.php.net to get a copy of this message
Two things always bugged me with array_rand(). First is its name. It does not sound clear enough whether it gives key or values. Second and more importantly is its erratic randomness, which is already well documented. That is why I came up with these two simple functions: <?php function random_key($array){ $keys=array_keys($array); return $keys[mt_rand(0, count($keys) - 1)]; } function random_value($array){ $values=array_values($array); return $values[mt_rand(0, count($values) - 1)]; } ?> They both work well with any kind of arrays, do not alter the original one like shuffle, are giving more realistic random results, and their names are self describing. The main drawback is that, as opposed to array_rand, they only gives one element, but at least that is clear from their name. I do believe easy to make random_keys and random_values. ---- Server IP: 72.52.91.14 Probable Submitter: 174.118.20.56 ---- Manual Page -- http://php.net/manual/en/function.array-rand.php Edit -- https://master.php.net/note/edit/115731 Del: integrated -- https://master.php.net/note/delete/115731/integrated Del: useless -- https://master.php.net/note/delete/115731/useless Del: bad code -- https://master.php.net/note/delete/115731/bad+code Del: spam -- https://master.php.net/note/delete/115731/spam Del: non-english -- https://master.php.net/note/delete/115731/non-english Del: in docs -- https://master.php.net/note/delete/115731/in+docs Del: other reasons-- https://master.php.net/note/delete/115731 Reject -- https://master.php.net/note/reject/115731 Search -- https://master.php.net/manage/user-notes.php

« previous php.notes (#200442) next »