random numbers

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

User avatar
Benjamin
Site Administrator
Posts: 6935
Joined: Sun May 19, 2002 10:24 pm

Re: random numbers

Post by Benjamin »

Actually the first one results in a parse error. I'm not sure they guarantee unique numbers either.

This was the direction I was headed, but it of course does not work because shuffle doesn't return anything useful.

Code: Select all

$random = array_slice(shuffle(range(0, 25000)), 0, 103);
This should work ok:

Code: Select all

$pool = range(0,25000);
shuffle($pool);
$random = array_slice($pool, 0, 103);
Maybe using a combination of array_map and array_rand would result in a good one liner.
User avatar
Eran
DevNet Master
Posts: 3549
Joined: Fri Jan 18, 2008 12:36 am
Location: Israel, ME

Re: random numbers

Post by Eran »

Actually the first one results in a parse error. I'm not sure they guarantee unique numbers either.
Works for me on PHP 5.3.1. Why would mt_rand() not guarantee random numbers?
User avatar
Benjamin
Site Administrator
Posts: 6935
Joined: Sun May 19, 2002 10:24 pm

Re: random numbers

Post by Benjamin »

Ah ok, I'm running 5.2.10.

Unique, not random.
User avatar
Eran
DevNet Master
Posts: 3549
Joined: Fri Jan 18, 2008 12:36 am
Location: Israel, ME

Re: random numbers

Post by Eran »

One liner (PHP 5.3 version)-
lambdas were added in 5.3
Unique, not random.
Ah, I see what you mean. Nice try though
User avatar
Jonah Bron
DevNet Master
Posts: 2764
Joined: Thu Mar 15, 2007 6:28 pm
Location: Redding, California

Re: random numbers

Post by Jonah Bron »

Foul! Multiple semicolons on one line!

@pytrin, Where's the shooting-self-in-head-with-gun emoticon?
Last edited by Jonah Bron on Mon Apr 26, 2010 2:52 pm, edited 1 time in total.
User avatar
Benjamin
Site Administrator
Posts: 6935
Joined: Sun May 19, 2002 10:24 pm

Re: random numbers

Post by Benjamin »

Figured it was possible. This isn't too inefficient either.

Code: Select all

$numbers = array_slice(array_unique(array_map(create_function('', 'return mt_rand(0,250000);'), range(0,150))), 0, 104);
Post Reply