= $N ? 0 : $x; if (! isset($board[$sy][$sx])) { // if empty - then assign number $board[$sy][$sx] = $i; $y = $sy; $x = $sx; } else { // else go down a row. $x-=1; $y+=2; $board[$y][$x] = $i; } } } // clean up sort the key correctly for($i = 0; $i < $N; $i++) { ksort($board[$i]); }; ksort($board); return $board; } print_r(solution(3)); // 3x3 print_r(solution(5)); // 5x5