What are the best practices for handling arrays in PHP when calculating sums?
When calculating sums of arrays in PHP, it is important to ensure that the array is properly validated before performing any calculations to avoid errors. One way to do this is by using the `is_array()` function to check if the input is indeed an array. Additionally, you can use the `array_sum()` function to easily calculate the sum of all values in the array.
// Validate input as an array and calculate sum
function calculateArraySum($arr) {
if (!is_array($arr)) {
return "Input is not an array";
}
$sum = array_sum($arr);
return $sum;
}
// Example usage
$array = [1, 2, 3, 4, 5];
echo calculateArraySum($array); // Output: 15