Code Logo

Sum and Count Even Numbers (PHP)

Published at24 Jul 2026
PHP Data Structures Easy 0 views
Like0

Write a PHP function that takes an array of integers and returns the sum of all even numbers in it.

The modulo operator % checks if a number is even: $n % 2 === 0 means the number is divisible by 2. Initialize a sum variable to 0. Loop through the array with foreach, check each element, and add to the sum if it's even.

PHP's foreach loop provides simple array iteration without needing index variables. The === operator ensures both value and type match, preventing type juggling issues.

Edge cases include empty arrays (return 0), arrays with no even numbers (return 0), negative even numbers (they still satisfy $n % 2 === 0), and zero (0 % 2 === 0, so 0 is even).

The time complexity is O(n) with a single pass. The space complexity is O(1) using only an accumulator variable.

Even numbers are those divisible by 2 with no remainder. The modulo operator % returns the remainder of division. For any even number $n, $n % 2 equals 0 because even numbers are multiples of 2. This property holds for both positive and negative even numbers.

PHP's type system handles integer arithmetic precisely for the range of values in typical test cases. The foreach loop iterates over each element without needing an index variable, making the code cleaner and less error-prone.

Example Input & Output

Example 1
Input
[2,4,6]
Output
12
Example 2
Input
[1,3,5]
Output
0
Example 3
Input
[]
Output
0
Example 4
Input
[-2,-4,1]
Output
-6
Example 5
Input
[1,2,3,4,5]
Output
6

Algorithm Flow

Recommendation Algorithm Flow for Sum and Count Even Numbers (PHP)
Recommendation Algorithm Flow for Sum and Count Even Numbers (PHP)

Solution Approach

Write a PHP function that takes an array of integers and returns the sum of all even numbers in it.

The modulo operator % checks if a number is even: $n % 2 === 0 means the number is divisible by 2. Initialize a sum variable to 0. Loop through the array with foreach, check each element, and add to the sum if it's even.

PHP's foreach loop provides simple array iteration without needing index variables. The === operator ensures both value and type match, preventing type juggling issues.

Edge cases include empty arrays (return 0), arrays with no even numbers (return 0), negative even numbers (they still satisfy $n % 2 === 0), and zero (0 % 2 === 0, so 0 is even).

The time complexity is O(n) with a single pass. The space complexity is O(1) using only an accumulator variable.

Best Answers

php - Approach 1
<?php
function sumEven($nums) {
    $s=0;foreach($nums as $n){if($n%2===0)$s+=$n;}return $s;
}