(PHP 5 >= 5.1.0, PHP 7, PHP 8)
array_product — Calculate the product of values in an array
array_product() returns the product of values in an array.
array
The array.
Returns the product as an integer or float.
Version | Description |
---|---|
8.3.0 |
Now emits E_WARNING when array values
cannot be converted to int or float .
Previously array s and object s where ignored whilst every other value was cast to int .
Moreover, objects that define a numeric cast (e.g. GMP ) are now cast instead of ignored.
|
Example #1 array_product() examples
<?php
$a = array(2, 4, 6, 8);
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
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.
Here's how you can find a factorial of a any given number with help of range and array_product functions.
function factorial($num) {
return array_product(range(1, $num));
}
printf("%d", factorial(5)); //120
Just a little correction for Andre D's answer: "(bool) array_product($array);" is equivalent with the conjunction of each array elements of $array, UNLESS the provided array is empty in which case array_product() will return 1, which will translate to boolean TRUE.
To mitigate this, you should expand the function with an additional check:
<?php
$result = !empty($check) && !!array_product($check);
?>
You can use array_product() to calculate the geometric mean of an array of numbers:
<?php
$a = [ 1, 10, 100 ];
$geom_avg = pow( array_product( $a ), 1 / count( $a ));
// = 9.999999999999998 ≈ 10
?>
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;
}
?>