note 49246 added to function.rand
| From: | relsqui at armory dot com | Date: | Fri, 21 Jan 2005 10:23:39 +0000 |
| Subject: | note 49246 added to function.rand | ||
| Groups: | php.notes | ||
| Request: | Send a blank email to php-notes+get-83723@lists.php.net to get a copy of this message | ||
Don't forget, it's faster to use bitwise operations when you need a random number
that's less than some power of two. For example,
<?php
rand()&1;
// instead of
rand(0,1);
// for generating 0 or 1,
rand()&3;
// instead of
rand(0,3);
// for generating 0, 1, 2, or 3,
rand()&7;
// instead of
rand(0,7)
// for generating 0, 1, 2, 3, 4, 5, 6, or 7,
?>
and so on. All you're doing there is generating a default random number (so PHP doesn't
have to parse any arguments) and chopping off the piece that's useful to you (using a bitwise
operation which is faster than even basic math).
----
Manual Page -- http://www.php.net/manual/en/function.rand.php
Edit -- http://master.php.net/manage/user-notes.php?action=edit+49246
Delete: added to the manual -- http://master.php.net/manage/user-notes.php?action=delete+49246&report=yes&reason=added+to+the+manual
Delete: bad code -- http://master.php.net/manage/user-notes.php?action=delete+49246&report=yes&reason=bad+code
Delete: spam -- http://master.php.net/manage/user-notes.php?action=delete+49246&report=yes&reason=spam
Delete: useless -- http://master.php.net/manage/user-notes.php?action=delete+49246&report=yes&reason=useless
Delete: other reasons -- http://master.php.net/manage/user-notes.php?action=delete+49246&report=yes
Reject -- http://master.php.net/manage/user-notes.php?action=reject+49246&report=yes
Search -- http://master.php.net/manage/user-notes.php