136. PHP Program to print Diagonal elements of a given matrix.
How does this program work?
- In this program we are going to learn about how to print Diagonal elements of a given matrix using PHP.
- Diagonal elements can display only when rows and columns of given matrix must be in equal.
Here is the code
<html>
<head>
<title>PHP Program To print Diagonals of a given matrix</title>
</head>
<body>
<?php
//Initialize A matrix
$a = array
(
array( 1, 2, 3, 4 ),
array( 2, 3, 4, 1 ),
array( 3, 4, 2, 1 ),
array( 4, 3, 2, 1 )
);
$m = count ($a);
$n = count ($a);
//If rows and columns are equal then print Diagonal elements else it returns to else statement
if($m==$n)
{
echo("Original matrix is: <br>"); // to print Original matrix
for($i = 0; $i < $m; $i++) {
for($j = 0; $j < $n; $j++) {
echo ($a[$i][$j] . " ");
}
echo("<br>");
}
echo ("Diagonal Elements are: </br>"); //to print Diagonal Elements
for ($i = 0; $i < $m; $i++)
{
echo $a[$i][$i], $a[$i][$n-$i-1];
echo "<br>";
}
}
else
echo "The given matrix is not a square matrix";
return 0;
?>
</body>
</html>