Print 2-D array in spiral order

$matrix = [
  [ 1,  2,  3,  4,  5],
  [ 6,  7,  8,  9, 10],
  [11, 12, 13, 14, 15],
  [16, 17, 18, 19, 20],
  [21, 22, 23, 24, 25]
];

spiral($matrix);

function spiral($matrix)
{
  $top = 0;
  $bottom = count($matrix) - 1;
  
  $left = 0;
  $right = count($matrix[0]) - 1;
  
  $direction = 0;
  // 0 = right, 1 = down, 2 = left, 3 = up
  
  while ($top <= $bottom && $left <= $right) {

    if ($direction == 0) {
      for ($i = $left; $i <= $right; $i++) {
        print "{$matrix[$top][$i]}\n";
      }
      $top++;
      $direction++;
    }

    if ($direction == 1) {
      for ($i = $top; $i <= $bottom; $i++) {
        print "{$matrix[$i][$right]}\n";
      }
      $right--;
      $direction++;
    }

    if ($direction == 2) {
      for ($i = $right; $i >= $left; $i--) {
        print "{$matrix[$bottom][$i]}\n";
      }
      $bottom--;
      $direction++;
    }

    if ($direction == 3) {
      for ($i = $bottom; $i >= $top; $i--) {
        print "{$matrix[$i][$left]}\n";
      }
      $left++;
      $direction = 0;
    }
  }  
}
    
index