Print matrix in diagonal pattern | php program to print matrix in diagonal order ; Initialize indexes of element to be printed next ; Direction is initially from down to up ; Traverse the matrix till all elements get traversed ; If isUp = true then traverse from downward to upward ; Set i and j according to direction ; If isUp = 0 then traverse up to down ; Set i and j according to direction ; Revert the isUp to change the direction ; Driver code
< ? php $ MAX = 100 ; function printMatrixDiagonal ( $ mat , $ n ) { $ i = 0 ; $ j = 0 ; $ isUp = true ; for ( $ k = 0 ; $ k < $ n * $ n { if ( $ isUp ) { for ( ; $ i >= 0 && $ j < $ n ; $ j ++ , $ i -- ) { echo $ mat [ $ i ] [ $ j ] . " " ; $ k ++ ; } if ( $ i < 0 && $ j <= $ n - 1 ) $ i = 0 ; if ( $ j == $ n ) { $ i = $ i + 2 ; $ j -- ; } } else { for ( ; $ j >= 0 && $ i < $ n ; $ i ++ , $ j -- ) { echo $ mat [ $ i ] [ $ j ] . " " ; $ k ++ ; } if ( $ j < 0 && $ i <= $ n - 1 ) $ j = 0 ; if ( $ i == $ n ) { $ j = $ j + 2 ; $ i -- ; } } $ isUp = ! $ isUp ; } } $ mat = array ( array ( 1 , 2 , 3 ) , array ( 4 , 5 , 6 ) , array ( 7 , 8 , 9 ) ) ; $ n = 3 ; printMatrixDiagonal ( $ mat , $ n ) ; ? >