0

I am searching for some kind of function or technique how to randomize/shuffle array based on parameter. I will try to describe what I am looking for.

Let's say we have:

$begin_array = array( 1,2,3,4,5,6,7,8,9,0 );

Then we call function:

magic_function( $begin_array, 1 );

And it returns the same randomized array every time based on second int argument of the function (1). If we provide 2, the returned array should be different from the first one but always in the same randomized order.

In other words this "magic" function should return randomized array based on the second integer argument.

The length of $begin_array is always different.

And the second argument can be up to 256.

Sample of what I am expecting:

<?php

$begin_array = array( 1,2,3,4,5,6,7,8,9,0 );

magic_function( $begin_array, 1 );
// always returns the same randomized array based on second int argument 1
// for ex: array( 5,2,1,8,3,9,6,4,7,0 );

magic_function( $begin_array, 2 );
// always returns the same randomized array based on second int argument 2
// for ex: array( 0,3,4,8,9,1,2,6,7,5 );

?>

I hope you understood me ;)

Thank you in advance, friends!

WebDevHere
  • 119
  • 1
  • 7

1 Answers1

0

What you're looking for is a shuffle function that uses a random function that is seeded by the second argument.

You can do this by translating this Javascript array shuffle answer into PHP, and seeding the random number generator with the second argument:

function deterministic_shuffle(array $array, $seed)
{
    mt_srand($seed); // set the initial state
    // shuffle implementation using mt_rand()
    mt_srand(); // seed it again with random value to avoid affecting other code
    return $array;
}
Community
  • 1
  • 1
Anonymous
  • 11,740
  • 3
  • 40
  • 50