PHP Program to print the identity matrix

What is an identity matrix?

The identity matrix is a square matrix of any order in which the diagonal(when the index of row and column are the same) elements are all 1, and all other elements in the matrix must be 0. For example, 

[ 1 0 0 ]

[ 0 1 0 ]

[ 0 0 1 ]

In the above matrix, we can see that all the diagonal values are 1 and others are 0 so we can say that this is an identity matrix.

How to print identity matrix using PHP?

To print the identity matrix first we have to initialize an empty array a[]. Then we have to accept the values into the variable rc from the user to store the number of rows and columns. After that to print the identity matrix using the for loop first assign the value 0 into the variable i and perform the sub-step until the condition 'i < row' becomes false and increment the value of variable i in every iteration and in the block of loop we have to perform another loop assign the value 0 into the variable j and perform the sub-step until the condition 'j < col' becomes false and increment the value of variable j in every iteration and in the block of this loop check condition 'i == j' if true then print 1 otherwise print 0

ALGORITHM

Step 1: Initialize an empty array a[]

Step 2: Accept the values into the variable rc from the user to store the number of rows and columns

Step 3: To print the identity matrix using the for loop first assign the value 0 into the variable i and perform the sub-step until the condition 'i < row' becomes false and increment the value of variable i in every iteration

        (i) Assign the value 0 into the variable j and perform the sub-step until the condition 'j < col' becomes false and increment the value of variable j in                every iteration

            (a) Check condition 'i == j' if true then print 1 otherwise print 0

PHP Source Code

                                          <?php
$a = array();
$rc = readline("Enter the number of rows and columns: \n");
echo "The entered matrix is matrix: \n";
for ($i = 0; $i < $rc; $i++) {
    for ($j = 0; $j < $rc; $j++) {
        if ($i == $j) {
            echo "1 ";
        } else {
            echo "0 ";
        }
    }
    echo "\n";
}
?>
                                      

OUTPUT

Enter the number of rows and columns:  5
The entered matrix is matrix:
1 0 0 0 0
0 1 0 0 0
0 0 1 0 0
0 0 0 1 0
0 0 0 0 1