Results 1 to 10 of 10
-
05-13-2004, 09:40 PM #1Web Hosting Master
- Join Date
- Mar 2004
- Location
- USA
- Posts
- 4,345
Another (interesting) PHP Question!
Lets say (dynamically) i have some numbers,
lets say 2 , 3 6, 7
I want to pick one of them randomly.. I can do it if the numbers are in order 0,1,2,3 ... I do not know how to do it if they are not ordered?
anyone tried it before?
Peace,
-
05-13-2004, 10:07 PM #2Web Hosting Master
- Join Date
- Jan 2003
- Location
- Perth, WA, Australia
- Posts
- 1,276
Where are these numbers stored? In a variable (string), like "2367" or in an array?
nu-metal.org :: coming soon
-
05-13-2004, 10:32 PM #3Web Hosting Master
- Join Date
- Mar 2004
- Location
- USA
- Posts
- 4,345
Originally posted by digitok
Where are these numbers stored? In a variable (string), like "2367" or in an array?
1|3|9 ..
I can easily put them into an array if it will help!
-
05-14-2004, 12:05 AM #4WHT Addict
- Join Date
- Aug 2003
- Location
- PA
- Posts
- 110
Go to this page at php.net. It covers a function called array_rand() and seeding.
Hope it was what you were looking for!
-
05-14-2004, 03:32 AM #5Junior Guru Wannabe
- Join Date
- May 2004
- Posts
- 57
-
05-14-2004, 05:38 AM #6Web Hosting Master
- Join Date
- May 2002
- Location
- UK
- Posts
- 2,997
If they are stored one per entry you can use the ORDER BY RAND() function in MySQL.
-
05-14-2004, 09:53 AM #7WHT Addict
- Join Date
- Aug 2003
- Location
- PA
- Posts
- 110
Although it can repick a number in consecutive fashion, the original poster only asked to pick at random.
And if they are in a DB, you should just use a SQL, or proprietary SQL, statement to call a random number as Rich pointed out.
You can also take your count of elements in the array, get a random, then do a modular calc on the number( % ), and use that random number as the array element.
Here is how to do it without using the PHP functions.
PHP Code:
$choices = array("2","3","6","7");
$elem = (rand() % count($choices));
$random_element = $choices[$elem];
Later
-
05-14-2004, 12:40 PM #8Web Hosting Master
- Join Date
- Mar 2004
- Location
- USA
- Posts
- 4,345
Originally posted by Rich2k
If they are stored one per entry you can use the ORDER BY RAND() function in MySQL.
SELECT * FROM banners Where `group`='general' ORDER BY RAND()
let me try that ( i will also look it up)..
sounds easier than extracting the numbers, choose one and the get it...
thnx alot guys for ur help
-
05-14-2004, 12:45 PM #9Web Hosting Master
- Join Date
- Mar 2004
- Location
- USA
- Posts
- 4,345
I did this:
it picks the same number each time?
PHP Code:$query_view_check = "SELECT * FROM stats WHERE `group`='$group' ORDER BY RAND() LIMIT 1";
$result_view_check = @mysql_query($query_view_check);
$num_view_check = @mysql_fetch_array($result_view_check);
echo $num_view_check[0];
-
05-14-2004, 03:04 PM #10Web Hosting Master
- Join Date
- Mar 2004
- Location
- USA
- Posts
- 4,345
Cool...
it didnt work for some reaon. its working now..
thnx guys