This morning in the IRC chat (irc.scriptschool.com #scriptschool) a random visitor named Rnd-Amarion stopped by with the following how-to PHP question:
I am about to learn PHP, and want to program a simple web page with a long string of random numbers. I have the random numbers allready. When someone queries the web site, it retrieves four of those numbers from the front of this list and gives them to the querier and then removes those numbers form the front fo the list.
I asked him what were the range of numbers he wanted randomized. While this information wasn’t critical to writing the code to solve this how-to, it would better demonstrate to him (her? I didn’t ask). Didn’t get a response but I decided to help this unknown person anyway.
Let’s consult the PHP manual for the function array_rand (PHP 4, 5) and the definition:
array_rand — Pick one or more random entries out of an array
That sounds like the right function, but with most programming languages there are many ways to approach the same problem. Let’s create some code to do this using the PHP functions range, shuffle and array_shift.
shuffle($random_numbers); // mix up the order
// return the first four numbers when queried and remove from array
$numbers_chosen = array($random_numbers[0], $random_numbers[1], $random_numbers[2], $random_numbers[3]);
print “Before: <br />”;
print_r($random_numbers); // show all random numbers
// remove first four numbers
for($i=0;$i<4;$i++) {
array_shift($random_numbers);
}
print“<hr />After: “;
print_r($random_numbers); // show all remaining random numbers
print“<hr />Chosen: “;
print_r($numbers_chosen); // first four numbers chosen
Example: code execution, code source
Notes: The array_shift function removes the first item in an array. The converse array_pop removes the last item in an array. Another useful array function is array_splice.
Update 9:55am PST: You can see a more efficient version using array_splice here that eliminates the use of the for loop in the code above and the use of array_shift. As for which is more efficient for removing only one item in the array, that’s a test for you to run :)

how can i use this php code?where do i paste it?..thanks..because im newbies about php codes..thanks alot godbless
on May 22nd, 2008 at 9:24 pm | #Link Comment