Check given matrix is magic square or not | Returns true if mat [ ] [ ] is magic square , else returns false . ; calculate the sum of the prime diagonal ; the secondary diagonal ; For sums of Rows ; check if every row sum is equal to prime diagonal sum ; For sums of Columns ; check if every column sum is equal to prime diagonal sum ; Driver Code
< ? php function isMagicSquare ( $ mat ) { $ sum = 0 ; $ N = 3 ; for ( $ i = 0 ; $ i < $ N ; $ i ++ ) $ sum = $ sum + $ mat [ $ i ] [ $ i ] ; $ sum2 = 0 ; $ N = 3 ; for ( $ i = 0 ; $ i < $ N ; $ i ++ ) $ sum2 = $ sum2 + $ mat [ $ i ] [ $ N - $ i - 1 ] ; if ( $ sum != $ sum2 ) return false ; for ( $ i = 0 ; $ i < $ N ; $ i ++ ) { $ rowSum = 0 ; for ( $ j = 0 ; $ j < $ N ; $ j ++ ) $ rowSum += $ mat [ $ i ] [ $ j ] ; if ( $ rowSum != $ sum ) return false ; } for ( $ i = 0 ; $ i < $ N ; $ i ++ ) { $ colSum = 0 ; for ( $ j = 0 ; $ j < $ N ; $ j ++ ) $ colSum += $ mat [ $ j ] [ $ i ] ; if ( $ sum != $ colSum ) return false ; } return true ; } { $ mat = array ( array ( 2 , 7 , 6 ) , array ( 9 , 5 , 1 ) , array ( 4 , 3 , 8 ) ) ; if ( isMagicSquare ( $ mat ) ) echo " Magic ▁ Square " ; else echo " Not ▁ a ▁ magic ▁ Square " ; return 0 ; } ? >