How to Create a PHP Function That Takes a List of Numbers and Returns the Sum of Even Numbers

We use a foreach loop to iterate through the array and check if each number is even using the modulo operator %.

Programmazione PHP
Programmazione PHP
Follow FullPress on Google

Add us to your preferred sources.

Follow this source on Google

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

Se vuoi rimanere aggiornato su How to Create a PHP Function That Takes a List of Numbers and Returns the Sum of Even Numbers iscriviti alla nostra newsletter settimanale

Be the first to comment

Leave a Reply

Your email address will not be published.


*