note 79235 added to function.array
| From: | jonhohle at osu1 dot php dot net | Date: | Fri, 16 Nov 2007 13:12:26 +0000 |
| Subject: | note 79235 added to function.array | ||
| Groups: | php.notes | ||
| Request: | Send a blank email to php-notes+get-132351@lists.php.net to get a copy of this message | ||
Here are shorter versions of sam barrow's functions. From a PHP perspective these are O(1)
(without getting into what's going on in the interpreter), instead of O(n).
<?php
function randomKey(array $array)
{
return randomElement(array_keys($array));
}
function randomElement(array $array)
{
if (count($array) === 0)
{
trigger_error('Array is empty.', E_USER_WARNING);
return null;
}
$rand = mt_rand(0, count($array) - 1);
$array_keys = array_keys($array);
return $array[$array_keys[$rand]];
}
?>
----
Server IP: 208.69.120.35
Probable Submitter: 70.190.176.4
----
Manual Page -- http://www.php.net/manual/en/function.array.php
Edit -- https://master.php.net/note/edit/79235
Del: integrated -- https://master.php.net/note/delete/79235/integrated
Del: useless -- https://master.php.net/note/delete/79235/useless
Del: bad code -- https://master.php.net/note/delete/79235/bad+code
Del: spam -- https://master.php.net/note/delete/79235/spam
Del: non-english -- https://master.php.net/note/delete/79235/non-english
Del: in docs -- https://master.php.net/note/delete/79235/in+docs
Del: other reasons-- https://master.php.net/note/delete/79235
Reject -- https://master.php.net/note/reject/79235
Search -- https://master.php.net/manage/user-notes.php