Sum and Count Even Numbers (PHP)
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
Algorithm Flow

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
function sumEven($nums) {
$s=0;foreach($nums as $n){if($n%2===0)$s+=$n;}return $s;
}Comments (0)
Join the Discussion
Share your thoughts, ask questions, or help others with this Challenge.
