What is the most efficient way to calculate the sum of specific elements in a multidimensional array in PHP?

When calculating the sum of specific elements in a multidimensional array in PHP, the most efficient way is to use a loop to iterate through the array and add up the desired elements. By targeting only the specific elements needed for the sum, unnecessary calculations can be avoided, resulting in a more efficient solution.

// Sample multidimensional array
$array = [
    [1, 2, 3],
    [4, 5, 6],
    [7, 8, 9]
];

// Initialize sum variable
$sum = 0;

// Calculate sum of specific elements (e.g., diagonal elements)
for ($i = 0; $i < count($array); $i++) {
    $sum += $array[$i][$i];
}

// Output the sum
echo "Sum of specific elements: " . $sum;