Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Semrush - keyword research tool

Turn ChatGPT, Claude, Gemini, And CoPilot Into Your Personal Assistant, Business Coach, Content Creator, And More

AFFILIATE MARKETING Your all-in-one performance engine Manage affiliates, creators, and customer referrals in one unified platform—turning every partnership into measurable growth
Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Boost your online presence with premium web hosting and servers

Disclosure: My content contains affiliate links.

42,844 questions

55,671 answers

573 users

How to check whether a matrix is a magic square or not in PHP

1 Answer

0 votes
// Function to check if the matrix is a magic square
function isMagicSquare(array $matrix): bool {
    $size = count($matrix); // number of rows
    $sumDiagonal1 = 0;
    $sumDiagonal2 = 0;

    // Calculate the sum of the primary diagonal
    for ($i = 0; $i < $size; $i++) {
        $sumDiagonal1 += $matrix[$i][$i];
    }

    // Calculate the sum of the secondary diagonal
    for ($i = 0; $i < $size; $i++) {
        $sumDiagonal2 += $matrix[$i][$size - $i - 1];
    }

    // If the two diagonals don't have the same sum, it's not a magic square
    if ($sumDiagonal1 !== $sumDiagonal2) {
        return false;
    }

    // Check sums of each row and column
    for ($i = 0; $i < $size; $i++) {
        $sumRow = 0;
        $sumCol = 0;

        for ($j = 0; $j < $size; $j++) {
            $sumRow += $matrix[$i][$j];  // Sum of the current row
            $sumCol += $matrix[$j][$i];  // Sum of the current column
        }

        // If any row or column sum is not equal to the diagonal sum, it's not a magic square
        if ($sumRow !== $sumDiagonal1 || $sumCol !== $sumDiagonal1) {
            return false;
        }
    }

    // If all checks pass, it's a magic square
    return true;
}

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

if (isMagicSquare($matrix)) {
    echo "The given matrix is a magic square.\n";
} else {
    echo "The given matrix is NOT a magic square.\n";
}



/*
run:

The given matrix is a magic square.

*/

 



answered Sep 30, 2025 by avibootz
...