Current Location: Home> Latest Articles> How to Calculate the Sum of Odd Numbers in an Array Using PHP | Quick Implementation Guide

How to Calculate the Sum of Odd Numbers in an Array Using PHP | Quick Implementation Guide

gitbox 2025-07-14

Introduction

In PHP programming, working with arrays is quite common. We often need to perform various operations on array elements, such as calculating the sum of odd numbers. This article will explain in detail how to calculate the sum of all odd numbers in an array using PHP, along with code examples.

Steps to Calculate the Sum of Odd Numbers in an Array

Creating the Array

First, create an array of integers as the base data for our calculation. Here's an example:

$numbers = array(1, 2, 3, 4, 5, 6, 7, 8, 9);

The array contains integers from 1 to 9.

Using a Loop to Traverse the Array

Next, we need to loop through each element of the array. We can use a foreach loop for this purpose:

$sum = 0;
foreach ($numbers as $number) {}

The $sum variable is used to store the sum of odd numbers, and it is initialized to 0.

Checking if an Element is Odd

Within the loop, we need to check if each element is odd. We can use the modulo operator (%) to check if a number is odd. If a number has a remainder of 1 when divided by 2, then it is odd.

if ($number % 2 == 1) {}

If the element is odd, we can perform operations like adding it to the $sum variable.

Calculating the Sum of Odd Numbers

Once we confirm an element is odd, we add its value to $sum:

$sum += $number;

This way, we accumulate the odd numbers in $sum.

Complete Code Example

Here is the complete code example:

$numbers = array(1, 2, 3, 4, 5, 6, 7, 8, 9);
$sum = 0;
foreach ($numbers as $number) {
    if ($number % 2 == 1) {
        $sum += $number;
    }
}
echo "The sum of odd numbers is: " . $sum;

Running this code will give you the sum of odd numbers in the array.

Sample Output

After running the above code, you will get the following result:

The sum of odd numbers is: 25

Conclusion

In this article, we learned how to calculate the sum of odd numbers in an array using PHP. First, we created an array containing integers. Then, we used a foreach loop to iterate through the array and checked if each element was odd. Finally, we added all odd numbers to $sum and displayed the result. We hope this tutorial helps you better understand PHP array operations.