数组 函数
在线手册:中文 英文
PHP手册

array_product

(PHP 5 >= 5.1.0)

array_product计算数组中所有值的乘积

说明

number array_product ( array $array )

array_product() 以整数或浮点数返回一个数组中所有值的乘积。

Example #1 array_product() 例子

<?php

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

?>

以上例程会输出:

product(a) = 384

参数

array

The array.

返回值

Returns the product as an integer or float.

范例

Example #2 array_product() examples

<?php

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

?>

以上例程会输出:

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


数组 函数
在线手册:中文 英文
PHP手册
PHP手册 - N: 计算数组中所有值的乘积

用户评论:

marcel dot glacki at stud dot fh-swf dot de (28-Sep-2010 04:36)

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;
}
?>

bishop (28-Jul-2009 06:34)

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; }
}
?>

hdeus at yahoo dot com (06-Oct-2008 04:25)

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);
   
   
}

?>

gmail at algofoogle (10-May-2007 05:18)

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

pqpqpq at wanadoo dot nl (17-Jan-2007 12:32)

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.

bishop (30-Nov-2006 03:13)

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; }
}

bishop (30-Nov-2006 03:04)

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.

marcel at computingnews dot com (15-Nov-2006 05:07)

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;
}

Andre D (07-Aug-2006 09:56)

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.

mattyfroese at gmail dot com (06-Jan-2006 02:25)

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