How can one efficiently arrange data in a spiral pattern within a rectangle using PHP?

To efficiently arrange data in a spiral pattern within a rectangle using PHP, you can create a nested loop to iterate over the rows and columns of the rectangle while keeping track of the current position and direction of the spiral. You can then fill in the data in a spiral pattern by incrementing the row or column based on the direction.

function spiralPattern($rows, $cols){
    $result = array_fill(0, $rows, array_fill(0, $cols, 0));
    
    $top = 0;
    $bottom = $rows - 1;
    $left = 0;
    $right = $cols - 1;
    
    $num = 1;
    
    while($top <= $bottom && $left <= $right){
        for($i = $left; $i <= $right; $i++){
            $result[$top][$i] = $num++;
        }
        $top++;
        
        for($i = $top; $i <= $bottom; $i++){
            $result[$i][$right] = $num++;
        }
        $right--;
        
        for($i = $right; $i >= $left; $i--){
            $result[$bottom][$i] = $num++;
        }
        $bottom--;
        
        for($i = $bottom; $i >= $top; $i--){
            $result[$i][$left] = $num++;
        }
        $left++;
    }
    
    return $result;
}

$rows = 4;
$cols = 4;
$result = spiralPattern($rows, $cols);

foreach($result as $row){
    echo implode(" ", $row) . "\n";
}