Accumulating Array Elements in PHP Loops
Let's use a loop to find the sum of the array elements:
<?php
$arr = [1, 2, 3, 4, 5];
$res = 0;
foreach ($arr as $elem) {
$res += $elem;
}
echo $res;
?>
Given an array:
<?php
$arr = [2, 5, 9, 3, 1, 4];
?>
Find the sum of the elements of this array.
Given an array:
<?php
$arr = [2, 5, 9, 3, 1, 4];
?>
Find the sum of the elements that are even numbers.
Given an array:
<?php
$arr = [2, 5, 9, 3, 1, 4];
?>
Find the sum of the squares of the elements of this array.
Given an array:
<?php
$arr = [2, 5, 9, 3, 1, 4];
?>
Find the product of the elements of this array.