PHP array_product() Function
Last Updated :
20 Jun, 2023
There are some point of time when we need to calculate the product of all elements in an array. The most basic way to do this is to iterate over all elements and calculate the product but PHP serves us with a builtin function to do this. The array_product() is a built-in function in PHP and is used to find the products of all the elements in an array.
Syntax:
array_product($array)
Parameters: The function takes only one parameter $array, that refers to the input array whose products of elements we wish to get.
Return Value: The array_product() function returns an integer or float value depending on the nature of elements of the array.
Examples:
Input : array = (5, 8, 9, 2, 1, 3, 6)
Output : 12960
Input : array = (3.2, 4.8, 9.1, 4.36, 1.14)
Output : 694.7426304
Below programs illustrates the working of array_product() function:
-
When the array passed to the array_product() function contains only integral values then the array_product() function returns an integer value equals to the product of all the elements of the array passed to it.
<?php
function Product( $array )
{
$result = array_product ( $array );
return ( $result );
}
$array = array (5, 8, 9, 2, 1, 3, 6);
print_r(Product( $array ));
?>
|
Output:
12960
-
When the array passed to the array_product() function contains both integral and float values then the array_product() function returns a floating point value equals to the product of all the elements of the array passed to it.
<?php
function Product( $array )
{
$result = array_product ( $array );
return ( $result );
}
$array = array (3.2, 4.8, 9.1, 4.36, 1.14);
print_r(Product( $array ));
?>
|
Output:
694.7426304
Reference:
http://php.net/manual/en/function.array-product.php
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...