To calculate the sum of the values in an array in PHP, you can use the array_sum()
function. This function returns the sum of all the values in the array.
For example:
$array = array(1, 2, 3, 4);
$sum = array_sum($array);
// $sum will be equal to 10
You can also use a loop to calculate the sum of the values in the array manually. For example:
$array = array(1, 2, 3, 4);
$sum = 0;
foreach ($array as $value) {
$sum += $value;
}
// $sum will be equal to 10
If you want to calculate the sum of the values in an associative array, you can use a loop like the one above and add the values of the array to the sum. For example:
$array = array('a' => 1, 'b' => 2, 'c' => 3, 'd' => 4);
$sum = 0;
foreach ($array as $value) {
$sum += $value;
}
// $sum will be equal to 10