Forum Moderators: coopster

Message Too Old, No Replies

Randomizing array using PHP

from mySQL selection

         

too much information

5:33 pm on Mar 9, 2006 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



I am trying to create a list of links that appear randomly with each page load. If I store the links in a mySQL database, how can I sort them randomly using PHP without getting any of the links more than once?

ChadSEO

5:48 pm on Mar 9, 2006 (gmt 0)

10+ Year Member



The array_rand() function could be very useful: http://us3.php.net/manual/en/function.array-rand.php

Basically it returns an array of keys, which can be a little confusing to use. You'll want to do something like this:

$r=@mysql_query("select url from url_table");
if(@mysql_num_rows($r))
while($field=mysql_fetch_field($r)) $result[]=$field;

$rand_keys = array_rand($result, 2);
echo $result[$rand_keys[0]] . "\n";
echo $result[$rand_keys[1]] . "\n";

Hope that helps, let me know if it needs clarification!

Chad

dreamcatcher

6:00 pm on Mar 9, 2006 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



I would let SQL do the work:

SELECT DISTINCT(link) FROM table ORDER BY rand()

dc