I need to create 3 array with 3 different random values from a simple php array. What is the best approach for that? Choosing random keys with array_rand()
then filter the keys from the array and choose another set of random keys again?
$input = array(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16);
Example output:
array1 : 4, 2, 7
array2 : 8, 3, 15
array3 : 16, 1, 11
Shuffle it, truncate it to 9 elements, chunk it in 3's.
Code: (Demo)
$input = array(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16);
shuffle($input);
var_export(array_chunk(array_slice($input,0,9),3));
Possible Output:
array (
0 =>
array (
0 => 5,
1 => 2,
2 => 11,
),
1 =>
array (
0 => 3,
1 => 8,
2 => 4,
),
2 =>
array (
0 => 12,
1 => 13,
2 => 15,
),
)