settingsAccountsettings
By using our mini forum, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy
Menusettings

Q: Array Rotation - PHP Array Task

+5 votes

Write a program that receives an array and number of rotations you have to perform (first element goes at the end).

Print the resulting array.

Examples:

array rotation php array task

asked in PHP category by user icabe

2 Answers

+4 votes

My answer:

<?php

$array = array_map('intval', explode(' ', readline()));
$rotations = intval(readline());
$count = count($array);
$rotations = $rotations % $count;

$newArray = [];

for ($i = $rotations; $i < $count; $i++) {
    $newArray[] = $array[$i];
}

for ($i = 0; $i < $rotations; $i++) {
    $newArray[] = $array[$i];
}

echo implode(' ', $newArray);
answered by user eiorgert
+3 votes

another solution with array_shift():

<?php

$array = array_map('intval', explode(' ', readline()));
$rotations = intval(readline());

for ($i = 0; $i < $rotations; $i++) {
    $first = array_shift($array);
    $array[] = $first;
}

echo implode(' ', $array);
answered by user john7
...