PHP Program to Check if a Matrix is Symmetric
Last Updated :
23 Jul, 2025
A square matrix is said to be a symmetric matrix if the transpose of the matrix is the same as the given matrix. A Symmetric matrix can be obtain by changing row to column and column to row.
Examples:
Input : [ [ 1, 2, 3 ],
[ 2, 1, 4 ],
[ 3, 4, 3 ] ]
Output : Yes
Input : [ [ 3, 5, 8 ],
[ 3, 4, 7 ],
[ 8, 5, 3 ] ]
Output : NoSimple solution-
- Create transpose of a given matrix.
- Check if transpose and given matrices are same or not.
PHP
<?php
// Simple PHP code for check a matrix is
// symmetric or not.
// Returns true if mat[N][N] is
// symmetric, else false
function isSymmetric($mat, $N) {
$tr = [[]];
for ($i = 0; $i < $N; $i++) {
for ($j = 0; $j < $N; $j++) {
$tr[$i][$j] = $mat[$j][$i];
};
}
// Fills transpose of
// mat[N][N] in tr[N][N]
for ($i = 0; $i < $N; $i++) {
for ($j = 0; $j < $N; $j++) {
if ($mat[$i][$j] != $tr[$i][$j]) {
return false;
}
};
}
return true;
}
// Driver code
$mat = [[1, 3, 5], [3, 2, 4], [5, 4, 1]];
if (isSymmetric($mat, 3)) {
echo "Yes";
} else {
echo "No";
}
?>
Time Complexity: O(N x N)
Auxiliary Space: O(N x N)
An Efficient solution to check a matrix is symmetric or not is to compare matrix elements without creating a transpose. We basically need to compare mat[i][j] with mat[j][i].
PHP
<?php
// Efficient PHP code for
// check a matrix is
// symmetric or not.
$MAX = 100;
// Returns true if mat[N][N]
// is symmetric, else false
function isSymmetric($mat, $N) {
for ($i = 0; $i < $N; $i++)
for ($j = 0; $j < $N; $j++)
if ($mat[$i][$j] != $mat[$j][$i])
return false;
return true;
}
// Driver code
$mat = array(array(1, 3, 5),
array(3, 2, 4),
array(5, 4, 1));
if (isSymmetric($mat, 3))
echo("Yes");
else
echo("No");
?>
Time Complexity: O(N x N)
Auxiliary Space: O(1)
Please refer complete article on Program to check if a matrix is symmetric for more details!
Explore
Basics
Array
OOPs & Interfaces
MySQL Database
PHP Advance