Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Shuffle array after 3rd element in foreach ? PHP

I need shuffle $items after 3rd element.

Result should be : 1 2 3 6 7 9 8 5 4

My is Code:

<?php
    $items= range(1, 10); shuffle($items); foreach($items as $v): 
?>
   ...
<?php 
  endforeach; 
?> 


Cant find any solution in stackoverflow or google.
How can I do this ?


Thanks in advance.


2 Answers

We can get first 3 elements and then shuffle others.

$items = range(1, 10);
for (var $i = 0; $i < 3; $i++) {
   $aRes[] = array_shift($items); 
}
shuffle($items);
foreach($items as $v) {
   $aRes[] = $v;
}
like image 141
Ivan Bolnikh Avatar answered May 06 '26 17:05

Ivan Bolnikh


Split the array in two parts and merge them after the suffle.

Edit; I now use array_splice to split the array at 3 and shuffle the remaining then merge them.

$items = range(1,10);
$items1= array_splice($items, 0,3);
shuffle($items);

$result = array_merge($items1, $items);
Var_dump($result);

https://3v4l.org/iUQ1m

like image 43
Andreas Avatar answered May 06 '26 17:05

Andreas



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!