How to Calculate Array Sum in PHP Without Using Built-in Functions
The array_sum function in PHP is a array function that calculates the sum of all numeric values in an array.
Here is a simple PHP code example that demonstrates how to calculate the sum of an array without using any built-in PHP functions:
<?php
// Function to calculate the sum of an array manually
function calculateArraySum($array) {
$sum = 0; // Initialize sum to zero
// Iterate through each element in the array
foreach ($array as $value) {
$sum += $value; // Add the value to the sum
}
return $sum; // Return the calculated sum
}
// Example usage
$numbers = [10, 20, 30, 40];
$result = calculateArraySum($numbers);
echo "The sum of the array is: " . $result;
?>
Output:
The sum of the array is: 100
Explanation:
- Input Array: An array of numbers is provided as input (e.g., [10, 20, 30, 40]).
- Initialization: A variable $sum is initialized to store the cumulative sum.
- Loop Through Array: Each value in the array is added to $sum using a foreach loop.
- Return the Sum: The function returns the final sum, which is then displayed.
Keep Learning 🙂