Can I select some (not all) elements in an array and shuffle them in PHP?

Is it possible to select some elements in an array and shuffle them in PHP? Know when you use

shuffle(array) 

it moves all the elements in the array, but I just want to shuffle some elements in the array while keeping the other elements unchanged, how do I do this?

+3
source share
2 answers

Consider the following

function swap(&$a, &$b) { list($a, $b) = array($b, $a); }

$len = count($a);
for($i = 0; $i < $len; $i++) {
   $j = rand(1, $len) - 1;
   swap($a[$i], $a[$j]);
}

this is a standard loop that moves all the elements of an array. To shuffle only some ("movable") elements, put their keys in an array

$keys = array(1, 3, 5, 7, 9, 11, 13, 17);

and replace the loop over $ a with the loop over $ keys

$len = count($keys);
for($i = 0; $i < $len; $i++) {
   $j = rand(1, $len) - 1;
   swap($a[$keys[$i]], $a[$keys[$j]]);
}

this moves the elements at positions 1, 3, 5, etc. and leaves other elements in place

+2

array_slice, , , , array_splice .

EDIT: , , , $keys. :

// Get out the items to shuffle.
$work = array();
foreach ($keys as $i => $key) {
    $work[$i] = $myarray[$key];
}

shuffle($work);  // shuffle them

// And put them back.
foreach ($keys as $i => $key) {
    $myarray[$key] = $work[$i];
}

(, , PHP , , !)

- . $keys , $myarray[$key] $myarray[$key[0]][$key[1]].

+1

Source: https://habr.com/ru/post/1723548/


All Articles