How to check whether a matrix is a square matrix in PHP

1 Answer

0 votes
function is_square(array $matrix): bool {
    $rows = count($matrix);

    foreach ($matrix as $row) {
        if (count($row) !== $rows) {
            return false; // If any row's length is not equal to the number of rows = not square
        }
    }

    return true; // All rows have the same length as the number of rows
}

$matrix = [
    [1, 2, 3],
    [4, 5, 6],
    [7, 8, 9]
];

echo is_square($matrix)
    ? "The matrix is a square matrix.\n"
    : "The matrix is not a square matrix.\n";



/*
run:

The matrix is a square matrix.

*/

 



answered Oct 7, 2025 by avibootz
...