Thursday, October 2, 2025
HomeData Modelling & AIPhp Program to Print matrix in snake pattern

Php Program to Print matrix in snake pattern

Given an n x n matrix in the given matrix, you have to print the elements of the matrix in the snake pattern.

Examples: 

Input :mat[][] = { {10, 20, 30, 40},
                   {15, 25, 35, 45},
                   {27, 29, 37, 48},
                   {32, 33, 39, 50}};
              
Output : 10 20 30 40 45 35 25 15 27 29
         37 48 50 39 33 32 
Input :mat[][] = { {1, 2, 3},
                   {4, 5, 6},
                   {7, 8, 9}};
Output : 1 2 3 6 5 4 7 8 9

Matrix printing
 

We traverse all rows. For every row, we check if it is even or odd. If even, we print from left to right else print from right to left. 

PHP




<?php
// PHP program to print
// matrix in snake order
$M= 4;
$N =4;
 
function printLN($mat)
{
    global $M;
    global $N;
     
    // Traverse through all rows
    for ($i = 0; $i < $M; $i++)
    {
 
        // If current row is even,
        // print from left to right
        if ($i % 2 == 0)
        {
            for ($j = 0; $j < $N; $j++)
                echo $mat[$i][$j], " ";
 
        // If current row is odd,
        // print from right to left
        }
        else
        {
            for ($j = $N - 1; $j >= 0; $j--)
                echo $mat[$i][$j] , " ";
        }
    }
}
 
// Driver code
$mat = array(array(10, 20, 30, 40),
             array(15, 25, 35, 45),
             array(27, 29, 37, 48),
             array(32, 33, 39, 50));
 
printLN($mat);
 
// This code is contributed by ajit
?>


Output : 

10 20 30 40 45 35 25 15 27 29 37 48 50 39 33 32 

Time complexity: O(n^2) for given n*n matrix

Auxiliary space: O(1)

Please refer complete article on Print matrix in snake pattern for more details!

Last Updated :
05 Aug, 2022
Like Article
Save Article


Previous

<!–

8 Min Read | Java

–>


Next


<!–

8 Min Read | Java

–>

RELATED ARTICLES

Most Popular

Dominic
32331 POSTS0 COMMENTS
Milvus
85 POSTS0 COMMENTS
Nango Kala
6703 POSTS0 COMMENTS
Nicole Veronica
11867 POSTS0 COMMENTS
Nokonwaba Nkukhwana
11927 POSTS0 COMMENTS
Shaida Kate Naidoo
6818 POSTS0 COMMENTS
Ted Musemwa
7080 POSTS0 COMMENTS
Thapelo Manthata
6775 POSTS0 COMMENTS
Umr Jansen
6776 POSTS0 COMMENTS