PASSWORD RESET

Your destination for complete Tech news

PHP

How to calculate the sum of values in an array in PHP?

351 0
< 1 min read

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

Leave A Reply

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.