-1

I have an array : [1, 4, 3, 0, 5] and the output I want is 60 Which is to get the product of the array without multiplying the zeros in php. But I'm having struggles on figuring it out. Does anyone know how to?

Amy
  • 1,114
  • 13
  • 35
  • 2
    Does this answer your question? [Remove zero values from a PHP array](https://stackoverflow.com/questions/2287404/remove-zero-values-from-a-php-array) – Don't Panic Jul 02 '20 at 03:49
  • @Don'tPanic Sorry, It doesn't answer my question. I don't want to remove the 0's. I just want to get the product without multiplying the zero's, if that makes sense. – Amy Jul 02 '20 at 03:53
  • yeah , but first you need to create temporary array without zero, then multiply it – jack Jul 02 '20 at 04:02
  • Sure it does - use `array_filter()` (or any of the answers in that question) to strip the zeros, then multiply the rest of the elements. Someone has already posted an answer posted here doing exactly that. – Don't Panic Jul 02 '20 at 04:04

4 Answers4

2

You could use array_reduce to compute the product, comparing the intermediate values with 0 before multiplication:

$array = [1, 4, 3, 0, 5];

$product = array_reduce($array, function ($c, $v) { return $c * ($v == 0 ? 1 : $v); }, 1);
echo $product;

Output:

60

Or alternatively, use array_filter to remove the 0 values and then use array_product on the result (note this does not modify the original array):

$product = array_product(array_filter($array));
echo $product;

Output:

60

Also note that since you only want to remove 0 values, which are false in a boolean context; you don't need a callback function for array_filter.

Demo on 3v4l.org

Nick
  • 138,499
  • 22
  • 57
  • 95
0

You can try this. You can use array_reduce function and pass 1 for base multiplication.

function multiply($carry, $item){
  if($item != 0){
    $carry *= $item;
  }
  return $carry;
}
$array = [1,4,3,0,5];
var_dump(array_reduce($array,'multiply', 1)); // int(60)
Harry Bomrah
  • 1,658
  • 1
  • 11
  • 14
0

You can use array_filter to remove the zero from an array.

function exclude_zero($var)
  {
   if($var != 0)
   {
   return $var;
   }
  }

$a1=[1, 4, 3, 0, 5];
$result = [];
$result[] = array_filter($a1,"exclude_zero");
$result = array_product($result[0]);
echo $result;

Output

60
Kunal Raut
  • 2,495
  • 2
  • 9
  • 25
0
  1. you can loop through the array and multiply the values in it if the value is not 0.

     $arr = [1, 4, 3, 0, 5];
     $value = 1;
     foreach($arr as $val){
         if($val !== 0){
             $value *=$val;
         }
        }
     echo $value; 
     //this will return 60
    
  2. You can use a combination of array_product and array_filter to get your answer.

    $product = array_product(array_filter($array));
    echo $product;
    //this will return 60.
    
Hirumina
  • 738
  • 1
  • 9
  • 23