user8504877
user8504877

Reputation:

mt_rand PHP - line of several numbers

is it possible to customize mt_rand to a function which gives me a line of numbers without repeats.

For example mt_rand(1,5) should give me 4,2,3,1,5 or something like that.

Upvotes: 0

Views: 59

Answers (2)

Gras Double
Gras Double

Reputation: 16383

This achieves what you ask in your question:

$results = range(1, 5);
shuffle($results);


For more complex needs, you can use Faker.

For instance the randomElements() method, here picking 5 non-duplicate numbers in the 1-10 range:

$faker = \Faker\Factory::create();

$results = $faker->randomElements(range(1, 10), 5, false);

(though, this can also be done with regular PHP easily:)

$pool = range(1, 10);
shuffle($pool);

$results = array_slice($pool, 0, 5);

Upvotes: 1

Andreas
Andreas

Reputation: 23958

Range and shuffle.

$arr =Range(1,5); // array with items 1->5

Shuffle($arr); // shuffle them 

Var_dump($arr);// output
// Or
Echo implode(",", $arr); // to match your expected output

https://3v4l.org/Usa65

Upvotes: 2

Related Questions