We use a foreach loop to iterate through the array and check if each number is even using the modulo operator %.
In this example, the sommaNumeriPari function takes an array of numbers as an argument. We use a foreach loop to iterate through the array and check if each number is even using the modulo operator %. If the number is even, it is added to the $somma variable. Finally, the function returns the sum of the even numbers.
In the example, we have an array of numbers from 1 to 10 and call the sommaNumeriPari function, passing the array as an argument. The result is then printed to the screen with the echo statement.
function sommaNumeriPari($numeri) {
$somma = 0;
foreach ($numeri as $numero) {
if ($numero % 2 == 0) {
$somma += $numero;
}
}
return $somma;
}
$numeri = array(1, 2, 3, 4, 5, 6, 7, 8, 9, 10);
$risultato = sommaNumeriPari($numeri);
echo "La somma dei numeri pari è: " . $risultato;
Pubblicato in PHP

Be the first to comment