homepage Welcome to WebmasterWorld Guest from
register, free tools, login, search, pro membership, help, library, announcements, recent posts, open posts,
Become a Pro Member

Visit PubCon.com
Home / Forums Index / Code, Content, and Presentation / PHP Server Side Scripting
Forum Library, Charter, Moderators: coopster & jatar k

PHP Server Side Scripting Forum

Order by rand() or array_rand()?
What is better and faster?

 1:07 am on Jan 7, 2005 (gmt 0)

Hi all!
What method is faster and better in order to get a randomly selected thing: to do "order by rand()" or add sql result to an array and then do array_rand()?
Thanks in advance.



 11:28 am on Jan 7, 2005 (gmt 0)

That's completely up to you ;)

I normally let the database do any processing I can in an application so all I have to deal with is the result set. That, and most databases are very fast at handling the task.


 9:27 pm on Jan 7, 2005 (gmt 0)

Thanks, coopster!
I assume that you've meant that "order by rand()" will be faster, am i right? If so, why so many ready scripts use the array thing?


 5:36 pm on Jan 8, 2005 (gmt 0)

It all really depends, for something like this I would recommend benchmarking over just taking the easy way out.

$timeparts = explode(' ',microtime());
$starttime = $timeparts[1].substr($timeparts[0],1);
for ($x=1;$x<=$totaltimes; $x++) {
// Put code to benchmark here
$timeparts = explode(' ',microtime());
$endtime = $timeparts[1].substr($timeparts[0],1);
echo ("Your code ran at about ".(bcsub($endtime,$starttime,6)/$totaltimes)." seconds per loop")


 11:47 pm on Jan 8, 2005 (gmt 0)

Thanks a lot, jshpro2!
I didn't knew how to do this.


 12:40 am on Jan 9, 2005 (gmt 0)

One advantage of using array_rand() in php, is if you are running mysql 4.0 and have query caching enabled.

MySQL will NOT cache a query with RAND() or NOW() in it for example, so it has to do the query each time. If it's a "select * from table" without the rand, then it will cache the result until the table is updated.

I think the answer depends on how many rows in the table.


 5:36 pm on Jan 11, 2005 (gmt 0)

Thanks, eaden,
that's an important tip!

Global Options:
 top home search open messages active posts  

Home / Forums Index / Code, Content, and Presentation / PHP Server Side Scripting
rss feed

All trademarks and copyrights held by respective owners. Member comments are owned by the poster.
Home ¦ Free Tools ¦ Terms of Service ¦ Privacy Policy ¦ Report Problem ¦ About ¦ Library ¦ Newsletter
WebmasterWorld is a Developer Shed Community owned by Jim Boykin.
© Webmaster World 1996-2014 all rights reserved