Hacker rank - Left rotation - PHP code feedback Here is the problem description - https://www.hackerrank.com/challenges/ctci-array-left-rotation/problem


  A left rotation operation on an array of size \$n\$ shifts each of the array's elements 1 unit to the left. For example, if 2 left rotations are performed on array \$[1,2,3,4,5]\$, then the array would become \$[3,4,5,1,2]\$.
  
  Given an array of \$n\$ integers and a number, \$d\$, perform \$d\$ left rotations on the array. Then print the updated array as a single line of space-separated integers.


I wanted to get some feedback on my solution for this problem, it's a task in the Hackerrank Cracking the Coding Interview series.
I am pretty sure the code is working fine, as it passes 7 of the 9 test cases, but is getting timed-out for the last two cases, since these cases are unknown, I wanted to get some expert feedback, as how can I optimize this code.

&lt;?php
    //$handle = fopen ("input_leftR.txt","r");
    $handle = fopen ("php://stdin","r");
    fscanf($handle,"%d %d",$n,$k); //n and k values are available from here
    $a_temp = fgets($handle);
    $a = explode(" ",$a_temp);
    array_walk($a,'intval');

    //My Code from below
    $i; $j; $temp;
    if($n&lt;0 || $n&gt;1000000 || $k&lt;0|| $k&gt;1000000 || count($a) &lt;=0)
        exit;
    for($i=0; $i&lt;$k%$n; $i++){
    //for($i=0; $i&lt;$k; $i++){
        for($j=0; $j&lt;$n-1; $j++){
            $temp = $a[$j];
            $a[$j] = $a[$j+1];
            $a[$j+1] = $temp;
        }
    }
    //array_walk($a,'intval');
    //print implode(" ", $a);
    /*foreach($a as $key=&gt;$value){
        printf("%d", $value);
        if($key&lt;$n-1)
            printf(" ");
    }*/ 

    for($i=0;$i&lt;$n;$i++){
    printf("%d", $a[$i]);

    if($i&lt;$n-1)
        printf(" ");
    }
?&gt;
Performance

Shifting the content of an array is a very expensive operation.
Lot's of assignments.

Realize that you don't really need to shift the content.
You can shift an offset index,
and use that shifted offset to print the desired output:

for ($i = 0; $i &lt; $n; $i++) {
    $shifted = ($i + $k) % $n;
    printf("%d", $a[$shifted]);

    if ($i &lt; $n-1) printf(" ");
}


Unnecessary statements

This is unnecessary, it serves no purpose at all, you can safely delete it:


$i; $j; $temp;



Input validation

Although input validation is a good practice,
in an online challenge you can trust that the input will be in the described format, and all values will be within the described ranges.
I haven't seen an exception to that yet.
So you don't need this kind of code:


if($n&lt;0 || $n&gt;1000000 || $k&lt;0|| $k&gt;1000000 || count($a) &lt;=0)
    exit;



Formatting

The code is very poorly formatted:


Indentation is inconsistent
No spaces between operators make it look extremely compact and hard to read


Try to follow the writing style of the snippet in my first point.