menu

arrow_back How do I make a clockwise permutation of an array?

by
1 vote
Hi, could you please tell me where the last element of the array goes and why [1] element is the same as the zero element?

I just need to make a permutation from 1,2,3,4,5,6, 7---> 7,1,2,3,4,5,6

$mylist2 = array(1,2,3,4,5,6,7);

$mylist2[0]=$mylist2[(count($mylist2)-1)];

$my = $mylist2;
$i=0;

while ($i < count($mylist2)-1) {

$mylist2[$i+1] = $my[$i];
echo"$mylist2[$i], ";
$i++;
}
THANK YOU!

3 Answers

by
 
Best answer
0 votes
Maybe there is a more elegant solution or there is a special function for this. Then my colleagues will surely correct me, but for now use this working option:

$mylist2 = array(1,2,3,4,5,6,7);

$count = count($mylist2);
$newArray = array();

foreach ( $mylist2 as $key => $value ) {
if ( ($count-1) == $key ) {
$newArray[0] = $value;
} else {
$newArray[$key+1] = $value;
}
}

ksort($newArray);
var_dump(implode(", ", $newArray));
by
1 vote
function rotateArray($arr, $shift) {
$shift %= count($arr);
array_unshift($arr, ...array_splice($arr, -$shift));
return $arr;
}


$arr = range(1, 7);

echo implode(', ', rotateArray($arr, 1)); // 7, 1, 2, 3, 4, 5, 6
echo implode(', ', rotateArray($arr, -3)); // 4, 5, 6, 7, 1, 2, 3
echo implode(', ', rotateArray($arr, 69)); // 2, 3, 4, 5, 6, 7, 1
by
2 votes
$data  = [1,2,3,4,5,6,7];
$last = array_pop($data);
array_unshift($data, $last);
echo implode(', ', $data);

P.s.: читайте доку php.net