欢迎各位兄弟 发布技术文章

这里的技术是共享的

You are here

php 数组相乘,PHP array_product():计算数组中所有元素的乘积 有大用

PHP array_product() 函数用来计算数组中所有元素的乘积,其语法如下:

number array_product ( array $arr )

如果数组 arr 的所有元素都是整数,则返回一个整数值;如果其中有一个或多个值是浮点数,则返回浮点数。

如果数组 arr 中存在非数值类型的元素,那么 PHP 会尝试将它们转换成一个数值,转换失败就作为 0 值。例如,字符串 "29.5" 会被转换成小数 29.5,字符串 "100abc" 会被转换成整数 100。

array_product() 函数的使用示例如下:

$a = array(2, 3, 10, 15);

echo array_product($a) . "
";

$b = array(2, 5.5, "10abc", "3.3");

echo array_product($b) . "
";

$c = array(4, 3.5, "0.1", "http://www.top300.cc/php/");

echo array_product($c);

?>

运行结果为:

900

363

0

数组 c 的乘积之所以为 0,是因为字符串 "http://www.top300.cc/php/" 转换成数字失败,得到一个 0 值,0 乘以任何值的结果都是 0。

来自 https://blog.csdn.net/weixin_32677301/article/details/115142893



array_product

(PHP 5 >= 5.1.0)

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

说明

number array_product ( array $array )

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

参数


  • array

  • 这个数组。


返回值

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

范例


Example #1 array_product() 例子

<?php

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

?>

以上例程会输出:

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



用户评论:

Marcel G (2010-09-28 08:36:54)

You can use array_product to calculate the factorial of n:
<?php
function factorial$n )
{
  if( 
$n $n 1;
  return 
array_productrange1$n ));
}
?>

If you need the factorial without having array_product available, here is one:
<?php
function factorial$n )
{
  if( 
$n $n 1;
  for( 
$p++; $n; ) $p *= $n--;
  return 
$p;
}
?>

bishop (2009-07-28 10:34:18)

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 (
== 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 (2008-10-06 08:25:02)

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 (2007-05-09 21:18:26)

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 (2007-01-17 04:32:43)

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 (2006-11-29 19:13:52)

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 (2006-11-29 19:04:23)

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 (2006-11-15 09:07:06)

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 (2006-08-07 13:56:19)

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 (2006-01-06 06:25:05)

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


来自  https://www.yiibai.com/manual/php/function.array-product.html


普通分类: