Matrix Addition Example Using PHP

The definition of Matrix Addition is adding one matrix by another matrix is obtained by just adding the corresponding entries of the matrices. In this tutorial, I am giving a matrix addition example using the PHP program.

The Below is an Example of Matrix Addition for Two Matrices

Suppose there is a matrix: a b
c d

There is another matrix: e f 
g h

Now the addition of two matrices will be: a+e b+f

c+g d+h

Here is a PHP Program Example for the Implementation of Matrix Addition

 

<html>
    <body>
        <?php
echo "<b>The First matrix is given below:-</b>"."<br>";
$a=array(array());// First two dimensional array declaration
$b=array(array());//Second two dimensional array declaration
$c=array(array());//Third two dimensional array declaration
$rows=4;
$cols=4;
$m=1;
$n=1;
for($i=0;$i<$rows;$i=$i+1)
{
    for($j=0;$j<$cols;$j=$j+1)
    {
        $a[$i][$j]=$m;
        echo $a[$i][$j]." ";
        $m=$m+1;
    }
    echo "<br>";
}
echo "<b>The second matrix is given below:-</b><br>";
for($i=0;$i<$rows;$i=$i+1)
{
    for($j=0;$j<$cols;$j=$j+1)
    {
        $b[$i][$j]=$n;
        echo $b[$i][$j]." ";
        $n=$n*1;
    }
    echo "<br>";
}
echo "<b>The Final matrix is given below:-</b>"."<br>";
for($i=0;$i<$rows;$i=$i+1)
{
    for($j=0;$j<$cols;$j=$j+1)
    {
        $c[$i][$j]=$a[$i][$j]+$b[$i][$j]; 
        echo $c[$i][$j]." ";
    }
    echo "<br>";
}
        ?>
    </body>
</html>

Output:

The First matrix is given below:-
1 2 3 4 
5 6 7 8 
9 10 11 12 
13 14 15 16 
The second matrix is given below:-
1 1 1 1 
1 1 1 1 
1 1 1 1 
1 1 1 1 
The Final matrix is given below:-
2 3 4 5 
6 7 8 9 
10 11 12 13 
14 15 16 17

Here firstly we have created two matrices and displayed, then we have performed the addition of two matrices using the statement here $c[$i][$j]=$a[$i][$j]+$b[$i][$j] and finally we have displayed the resultant matrix.

Leave a Comment