downloads | documentation | faq | getting help | mailing lists | licenses | wiki | reporting bugs | php.net sites | conferences | my php.net

search for in the

array_push> <array_pop
[edit] Last updated: Fri, 26 Apr 2013

view this page in

array_product

(PHP 5 >= 5.1.0)

array_productCalculate the product of values in an array

Description

number array_product ( array $array )

array_product() returns the product of values in an array.

Parameters

array

The array.

Return Values

Returns the product as an integer or float.

Changelog

Version Description
5.3.6 The product of an empty array is now 1, when before this function would return 0 for an empty array.

Examples

Example #1 array_product() examples

<?php

$a 
= array(2468);
echo 
"product(a) = " array_product($a) . "\n";
echo 
"product(array()) = " array_product(array()) . "\n";

?>

The above example will output:

product(a) = 384
product(array()) = 1



array_push> <array_pop
[edit] Last updated: Fri, 26 Apr 2013
 
add a note add a note User Contributed Notes array_product - [10 notes]
up
0
gmail at algofoogle
5 years ago
Just in relation to "bishop" and the overall behaviour of array_product... The "empty product" (i.e. product of no values) is supposed to be defined as "1":

http://en.wikipedia.org/wiki/Empty_product

...however PHP's array_product() returns int(0) if it is given an empty array. bishop's code does this, too (so it IS a compatible replacement). Ideally, array_product() should probably return int(1). I guess it depends on your specific context or rationale.

You might normally presume int(0) to be a suitable return value if there are no inputs, but let's say that you're calculating a price based on "percentage" offsets:

$price = 10.0;
$discounts = get_array_of_customer_discounts();
$price = $price * array_product($discounts);

...if there are NO "discounts", the price will come out as 0, instead of 10.0
up
0
pqpqpq at wanadoo dot nl
6 years ago
An observation about the _use_ of array_product with primes:

$a=$arrayOfSomePrimes=(2,3,11);
              // 2 being the first prime (these days)

$codeNum=array_product($a); // gives 66 (== 2*3*11)

echo "unique product(\$a) = " . array_product($a) . "\n";

The 66 can (only) be split into its original primes,
which can be transformed into their place in the row of primes (2,3,5,7,11,13,17,19...)  giving (1,2,3,4,5,6,7,8...)

The 66 gives the places {1,2,5} in the row of primes. The number "66" is unique as a code for {1,2,5}

So you can define the combination of table-columns {1,2,5} in "66". The bigger the combination, the more efficient in memory/transmission, the less in calculation.
up
-1
bishop
3 years ago
gmail @ algofoogle is right, so we can extend our own array_product() to flexibly accept the empty product value.  Zero (0) is the default (to be compatible with PHP behavior), but you could change this to 1 for mathematical purposes or null for logical.

<?php
if (! function_exists('array_product')) {
    function
array_product($array, $emptyProduct = 0) {
        if (
is_array($array)) {
            return (
0 == count($array) ? $emptyProduct : array_reduce($array, '_array_product', 1));
        } else {
           
trigger_error('Param #1 must be an array', E_USER_ERROR);
            return
false;
        }
    }
    function
_array_product($v,$w) { return $v * $w; }
}
?>
up
0
Marcel G
2 years ago
You can use array_product to calculate the factorial of n:
<?php
function factorial( $n )
{
  if(
$n < 1 ) $n = 1;
  return
array_product( range( 1, $n ));
}
?>

If you need the factorial without having array_product available, here is one:
<?php
function factorial( $n )
{
  if(
$n < 1 ) $n = 1;
  for(
$p++; $n; ) $p *= $n--;
  return
$p;
}
?>
up
0
bishop
6 years ago
Yet another implementation of array_product() using PHP's native array_reduce():

if (! function_exists('array_product')) {
    function array_product($array) {
        if (is_array($array)) {
            return (0 == count($array) ? 0 : array_reduce($array, '_array_product', 1));
        } else {
            trigger_error('Param #1 must be an array', E_USER_ERROR);
            return false;
        }
    }
    function _array_product($v,$w) { return $v * $w; }
}
up
-1
hdeus at yahoo dot com
4 years ago
Here is how you can multiply two arrays in the form of matrixes using a bit of matrix algebra (M*M).
By calling the function multiplyMatrix, you will be multiplying two sparse matrixes (zeros need not be included in the array for the operation to be performed).

<?php
$M
= array(
0=>array(1=>1,4=>1),
1=>array(2=>1,3=>1),
3=>array(1=>1),
4=>array(5=>1),
5=>array(6=>1)
);

$M1 = multiplyMatrix($M, $M); //multiplying $M by itself

echo '<pre>';print_r($M1);echo '</pre>';

function
multiplyMatrix($M1, $M2)
    {
#Helena F Deus, Oct 06, 2008
##Multiply two matrixes; $M1 and $M2 can be sparse matrixes, the indexes on both should match
       
if(is_file($M1)) {$matrix1 = unserialize(file_get_contents($M1));}
        else
$matrix1 = $M1;
       
           
       
#transpose M2
       
$M2t = transpose($M2);
       
        foreach (
$M2t as $row=>$tmp) {
           
##sum the result of the value in the col multiplied by the value in the vector on the corresponding row
               
               
foreach ($M1 as $row1=>$tmp1) {
                   
                   
$multiply[$row1] = array_rproduct($tmp,$tmp1);
                   
                    if(!
$multiply[$row1]){
                          exit;
                        }
                }
               
                foreach (
$multiply as $row1=>$vals) {
                   
                   
$sum[$row][$row1]=array_sum($vals);
                }
               
        }
   
   
$r=transpose($sum);
   
    return (
$r);
    }

function
transpose($M)
{
foreach (
$M as $row=>$cols) {
           
            foreach (
$cols as $col=>$value) {
                 if(
$value)
                
$Mt[$col][$row]=$value;
            }
        }
       
ksort($Mt);
       
return (
$Mt);           
}

function
array_rproduct($a1, $a2)
{
   
   
    foreach (
$a1 as $line=>$cols) {
       
$a3[$line] = $a1[$line]*$a2[$line];
        foreach (
$a2 as $line2=>$cols2) {
           
$a3[$line2] = $a1[$line2]*$a2[$line2];
        }
    }   
   
ksort($a3);
   
   
    return (
$a3);
   
   
}

?>
up
-1
marcel at computingnews dot com
6 years ago
if you don't have PHP 5.xx . you can use this function.
It does not make sure that the variables are numeric.

function calculate_array_product($array="")
{
if(is_array($array))
    {
                foreach($array as $key => $value)
        {
            $productkey = $productkey + $key;
         }
       return $productkey;
    } 
  return NULL;
}
up
-1
Andre D
6 years ago
This function can be used to test if all values in an array of booleans are TRUE.

Consider:

<?php

function outbool($test)
{
    return (bool)
$test;
}

$check[] = outbool(TRUE);
$check[] = outbool(1);
$check[] = outbool(FALSE);
$check[] = outbool(0);

$result = (bool) array_product($check);
// $result is set to FALSE because only two of the four values evaluated to TRUE

?>

The above is equivalent to:

<?php

$check1
= outbool(TRUE);
$check2 = outbool(1);
$check3 = outbool(FALSE);
$check4 = outbool(0);

$result = ($check1 && $check2 && $check3 && $check4);

?>

This use of array_product is especially useful when testing an indefinite number of booleans and is easy to construct in a loop.
up
-1
mattyfroese at gmail dot com
7 years ago
If you don't have PHP 5

$ar = array(1,2,3,4);
$t = 1;
foreach($ar as $n){
    $t *= $n;
}
echo $t; //output: 24
up
-2
bishop
6 years ago
Regarding Andre D function to test if all values in an array of booleans are true, you can also use:

<?php
$allTrue
= (! in_array(false, $arrayToCheck));
?>

Both this method and Andre D's are O(n), but this method has a lower k in the average case: in_array() stops once it finds the first false, while array_product must always traverse the entire array.

 
show source | credits | stats | sitemap | contact | advertising | mirror sites