How to find even numbers in array in PHP?

by hal.littel , in category: PHP General , 2 years ago

How to find even numbers in array in PHP?

Facebook Twitter LinkedIn Telegram Whatsapp

2 answers

by ryan.murray , 2 years ago

@hal.littel use foreach loop to over array to find if a number is evenly divisible by 2 with no remainder, then it is even, here is PHP implementation:


 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
<?php

$arr = [1, 2, 3, 4, 5, 6, 7, 8];

// Loop over array
foreach ($arr as $number) {
    // Check if the number is even or not.
    if ($number & 2 === 0) {
        echo $number . PHP_EOL;
    }
}


by darrion.kuhn , a year ago

@hal.littel 

The code above will produce the output:


2 4 6 8