简体   繁体   中英

Product of even and odd numbers in PHP

So I need to find the product of the even and odd numbers from the array. So far I've only managed to identify which ones are odd and which even.

<?php
$array = array('2','1','1','6','3');

foreach($array as $v){
    if($v%2==0){
        $even = $v;
    } else{
        $odd = $v;
    }
}

How could I multiply the even numbers with one another (and the odd ones as well)?

First init the vars, set them to 1. The first iteration will just be 1*$v which is fine. Then use *= operator which is shorthand for $even = $even * $v;

<?php
$array = array('2','1','1','6','3');

$even = 1;
$odd = 1;
foreach($array as $v){
    if($v%2==0){
        $even *= $v;
    } else{
        $odd *= $v;
    }
}

edit

Here's a '1 liner' (well, 2 if you count initing the array)

$p=array(1,1);
array_walk($array,function($v)use(&$p){$p[$v%2]*=$v;});

//$p[0] will be product of evens
//$p[1] will be product of odds

Use the *= operator

$even = 1;
$odd = 1;
foreach($array as $v){
    if($v%2==0){
        $even *= $v;
    } else{
        $odd *= $v;
    }
}
function filter($values, $function) {
    return array_filter(
        $values,
        $function
    );
}

$isEven = function ($value) {
    return !($value & 1);
};

$isOdd = function ($value) {
    return $value & 1;
};

$data = array('2','1','1','6','3');

$odds = array_product(
    filter(
        $data,
        $isOdd
    )
);

$evens = array_product(
    filter(
        $data,
        $isEven
    )
);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM