Perform Matrix Division in PHP

Beginner
⏱️ 11 min read
📚 Updated: May 2026
🎯 2 Code Examples
Tables & division

What you’ll learn

  • In plain English: how to divide two same-sized tables by dividing matching cells (like stacking two spreadsheets and dividing top ÷ bottom in each cell).
  • Why programs here use float numbers, and why divide-by-zero must be handled.
  • Two short PHP examples: a straight 2×2 demo and a version that refuses to divide when the bottom cell is zero.

Overview

Picture two grids with the same number of rows and columns. For each box, you divide the number on top by the number directly below it. That is all this lesson implements in PHP. We call it element-wise division.

Two programs

A tiny 2×2 example with decimals, plus a safe version that checks for zeros.

Live preview

See the same numbers as example 1 computed in your browser.

Honest wording

We separate this simple idea from harder “inverse matrix” math so beginners do not get lost.

Before you start

You only need basic arithmetic (division), plus the idea of a loop that visits each row and column.

  • You can read a tiny PHP script with functions and echo.
  • You know that dividing by zero is not allowed.

In plain English

A matrix here is just a rectangle of numbers. If matrix A and matrix B have the same shape, the result in row i, column j is:

answer[i][j] = A[i][j] ÷ B[i][j]

Example: top-left is 4 ÷ 2 = 2, next cell is 8 ÷ 4 = 2, and so on. Each spot is independent: you never mix numbers from different boxes.

Later, you may hear “inverse matrices”

In advanced courses, “dividing by a matrix” can mean something deeper (multiply by an inverse). This tutorial does not do that. It only divides number-by-number in matching cells. Both ideas are real; they are not the same program.

Pocket calculator picture

Treat each pair like pressing “A cell ÷ B cell” on a calculator.

4 ÷ 2 = 2
Where
Top-left of the 2×2 example
8 ÷ 4 = 2
Where
Top-right of the same example

Every other cell in the sample works the same way. That is why the final table is all 2.00 in this particular exercise.

Live preview

These are the same starting numbers as code example 1. Press the button to see A, B, and A ÷ B (cell by cell).

No typing needed—good for a quick check before you compile.

Live result
Press “Show 2×2 division”.

Algorithm (simple steps)

Goal: fill a new table so each cell equals the top number divided by the bottom number in that cell.

Line up the grids

Both tables must have the same height and width. If they do not, this simple method does not apply.

Walk each row and column

Use one loop for rows and one loop for columns (nested loops). Visit every cell once.

Divide carefully

Before dividing, make sure the bottom value is not zero. Then store a[i][j] / b[i][j] in the answer table.

📜 Pseudocode

Pseudocode
function divide_elementwise(A, B, Result, rows, cols):
    for i from 0 to rows - 1:
        for j from 0 to cols - 1:
            if B[i][j] is zero:
                stop with an error (cannot divide)
            Result[i][j] ← A[i][j] / B[i][j]
1

Simple 2×2 element-wise division

This mirrors the old PHP sample idea: divide matching cells and print decimal-friendly output.

c
<?php
function printMatrix(array $matrix): void
{
    foreach ($matrix as $row) {
        foreach ($row as $value) {
            echo number_format((float)$value, 2) . "\t";
        }
        echo "\n";
    }
}

function matrixDivision(array $matrixA, array $matrixB): array
{
    $result = [];
    for ($i = 0; $i < count($matrixA); $i++) {
        for ($j = 0; $j < count($matrixA[$i]); $j++) {
            $result[$i][$j] = $matrixA[$i][$j] / $matrixB[$i][$j];
        }
    }
    return $result;
}

$matrixA = [[4.0, 8.0], [2.0, 6.0]];
$matrixB = [[2.0, 4.0], [1.0, 3.0]];

$result = matrixDivision($matrixA, $matrixB);
echo "Result of matrix division:\n";
printMatrix($result);
?>
2

Safer version with zero checks

Checks shape and blocks divide-by-zero before computing each result cell.

c
<?php
function safeMatrixDivision(array $a, array $b): array
{
    $rows = count($a);
    if ($rows !== count($b)) {
        throw new InvalidArgumentException("Matrices must have same row count.");
    }

    $result = [];
    for ($i = 0; $i < $rows; $i++) {
        if (count($a[$i]) !== count($b[$i])) {
            throw new InvalidArgumentException("Matrices must have same column count in each row.");
        }

        for ($j = 0; $j < count($a[$i]); $j++) {
            if ((float)$b[$i][$j] == 0.0) {
                throw new DivisionByZeroError("Cannot divide by zero at [$i][$j].");
            }
            $result[$i][$j] = $a[$i][$j] / $b[$i][$j];
        }
    }

    return $result;
}

$matrixA = [[6.0, 9.0], [12.0, 15.0]];
$matrixB = [[3.0, 3.0], [4.0, 5.0]];

try {
    $result = safeMatrixDivision($matrixA, $matrixB);
    foreach ($result as $row) {
        echo implode(" ", array_map(fn($v) => number_format((float)$v, 2), $row)) . "\n";
    }
} catch (Throwable $e) {
    echo "Error: " . $e->getMessage() . "\n";
}
?>

Going further (optional)

Bigger tables. Change ROWS and COLS, or read sizes from the user, as long as both matrices still match.

Need true matrix division in the math-club sense? That usually means learning matrix inverses and matrix multiplication. Treat that as a separate project; this page stays with the easy cell-by-cell idea.

❓ FAQ

Yes. Think of a matrix as a table of numbers. This program only does normal division in each box: top number ÷ bottom number in the same box. No special math course is required for that part.
It builds a new table. In every row and column, it takes the value from matrix A, divides it by the value from matrix B in the same position, and stores the answer. That is called element-wise (or entry-wise) division.
Often, no. In higher math, dividing by a matrix can mean multiplying by an inverse matrix. This tutorial does the simpler thing: divide matching cells. We say that clearly so you are not surprised later.
Division often gives decimals (for example 5 ÷ 2 = 2.5). The type float can store those decimal answers. int would drop the fraction or surprise you with rounding.
You cannot divide by zero. The first example only uses safe numbers. The second program checks before dividing and stops with a clear error message if it finds a zero in the bottom matrix.
It visits every cell once, so the time grows in proportion to the number of cells (rows times columns). Memory is small: you mostly store the two input tables and the result.

🔄 Input and output

These samples put numbers directly in the code. To try your own values, change the tables inside main (or later learn scanf to type them at runtime). Always keep A and B the same size, and keep every B cell nonzero unless you add error handling.

Watch out for

Three practical reminders while you are learning:

Zero

Division by zero

Never divide if the bottom cell is zero. Example 2 shows one simple guard.

Shape

Mismatched tables

This method needs the same number of rows and columns in both matrices.

Words

Name confusion

Say “element-wise division” if a teacher asks, so they know you mean cell-by-cell, not inverse matrices.

⏱️ Time and space (big picture)

TaskTimeExtra memory
Divide two m × n tables this wayProportional to m · n (each cell once)Small: mostly the output table

You do not need to memorize symbols here. The idea is: bigger grids take longer because there are more cells.

Summary

  • Idea: divide each top cell by the bottom cell in the same position. Same shape for both tables.
  • Code: two nested loops and float division; guard against zero if inputs vary.
  • Not the same as: multiplying by an inverse matrix (advanced topic).
Did you know?

This page uses cell-by-cell division: each number is only divided by the number in the same row and column. That is a simple idea. University math also talks about A × B−1 for “dividing” matrices—that is a different, harder topic.

About the author

Mari Selvan M P
Mari Selvan M P 🔗

Developer, cloud engineer, and technical writer

  • Experience 12 years building web and cloud systems
  • Focus Full Stack Development, AWS, and Developer Education

I write practical tutorials so students and working developers can learn by doing—from databases and APIs to deployment on AWS.

8 people found this page helpful