PHP Exercises: Count even number of elements in a given array of integers
PHP Basic Algorithm: Exercise-106 with Solution
Write a PHP program to count even number of elements in a given array of integers.
Sample Solution:
PHP Code :
<?php
// Define a function named 'test' that takes an array of numbers as a parameter
function test($nums)
{
// Initialize a variable named $evens with a value of 0
$evens = 0;
// Iterate through the elements of the array using a for loop
for ($i = 0; $i < sizeof($nums); $i++)
{
// Check if the current element is even (divisible by 2), increment $evens if true
if ($nums[$i] % 2 == 0) $evens++;
}
// Return the count of even elements in the array
return $evens;
}
// Call the 'test' function with an array [1, 5, 7, 9, 10, 12] and print the result
echo "Number of even elements: ". test([1, 5, 7, 9, 10, 12] );
?>
Sample Output:
Number of even elements: 2
Flowchart:
PHP Code Editor:
Contribute your code and comments through Disqus.
Previous: Write a PHP program to create a new array taking the first two elements from a given array. If the length of the given array is less than 2 then return the give array.
Next: Write a PHP program to compute the difference between the largest and smallest values in a given array of integers and length one or more.
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.
It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.
https://w3resource.com/php-exercises/basic-algorithm/php-basic-algorithm-exercise-106.php
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics