Move 2 records from array to array randomly?

I’m trying to figure out how to get 2 or more records moved from one array to another randomly?

This is what I have so far:

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

$random = rand(0,sizeof($array1)-1);

$getfromarray = $array1($random);

unset($array1[$random]);

As above I can get one number from the array above and remove it from the array, but not sure how to get multiple from the array and how to insert it into a new array?

Please help and thanks in advance :slight_smile:

Try this:


<?php
$array1 = array('1', '2', '3', '4', '5', '6', '7', '8', '9');
$array2 = array();
$numElements2del = 3;
for ($i = 0; $i < $numElements2del; $i++) {
    $random = rand(0, sizeof($array1) - 1);
    $array2[] = $array1[$random];
    array_splice($array1, $random, 1);
}
print_r($array1);
print_r($array2);
?>

If you don’t care about maintaining the order of the elements in the source array, you can shuffle it and pop off two elements. If you are trying to simulate playing cards this is likely the better solution since the deck state can be maintained over time.


$array1 = range(1,9);
$array2 = array();

shuffle($array1);

$array2[] = array_pop($array1);
$array2[] = array_pop($array1);