Codility cyclic rotation solution in PHP Problem statement

A zero-indexed array A consisting of N integers is given. Rotation of the array means that each element is shifted right by one index, and the last element of the array is also moved to the first place.

For example, the rotation of array A = [3, 8, 9, 7, 6] is [6, 3, 8, 9, 7]. The goal is to rotate array A K times; that is, each element of A will be shifted to the right by K indexes.

My Solution

function solution($A, $K) {
   // when array is empty or has only one element 
   if(count($A) == 0 || count($A) == 1){
        return $A;
    }
    //runs k times
    for($j=1; $j&lt;=$K; $j++){
        $last_element = $A[count($A)-1];
        //runs for each element
        for($i=(count($A)-1); $i&gt;0; $i--){
            $A[$i] = $A[$i-1];
        }
        $A[0] = $last_element;  
    }
    return $A;
}

$A = [1, 2, 3, 4];
$K = 4;
$result = solution($A, $K);
print_r($result);


Output

Array
(
    [0] =&gt; 1
    [1] =&gt; 2
    [2] =&gt; 3
    [3] =&gt; 4
)
You could use array functions. They simplify and speed up the handling of arrays. See: http://php.net/manual/en/ref.array.php

So your code could become:

function rotateArray($inputArray,$rightShiftCount)
// shift all elements of the array to the right a number of times
{
  // extract the part of the array to move to the front
  $partToMove = array_splice($inputArray,-($rightShiftCount % count($inputArray)));
  // return extract part followed by what was left of the array
  return array_merge($partToMove,$inputArray);
}


This function does not check its arguments, if needed you can add that.

Notice that I have used sensible names for my variables instead of $A and $K. This is intentional.