Skip to content
Home » PHP array_product() Function | Calculate Product Of An Array in PHP

PHP array_product() Function | Calculate Product Of An Array in PHP

In this tutorial let’s learn about PHP array_product() Function and also How to Calculate Product Of An Array in PHP.

PHP array_product() Function

There are times when we need to compute the product of all elements in an array. The most simple approach to accomplish this is to loop through all elements and calculate the product, however PHP provides us with a built-in function to accomplish this. The array_product() method is a built-in PHP function that finds the products of all the elements in an array.

Syntax

array_product($array)

The function accepts only one parameter, $array which refers to the input array whose elements’ products we want to calculate.

Depending on the nature of the array’s elements, the array_product() function returns an integer or a float value.

Calculate Product Of An Array using array_product() in PHP

When the array provided to the array_product() function contains only integral values, the array_product() function returns an integer value equal to the product of all the array’s elements.

Code Example :

<?php

function Product($array)
{
	$result = array_product($array);
	return($result);
}

$array = array(1,2,3,4);
print_r(Product($array));
?>

Output :

24

When the array provided to the array_product() function contains both integral and float values, the array_product() function yields a floating point value equal to the product of the array’s elements.

Code Example :

<?php


function Product($array)
{
	$result = array_product($array);
	return($result);
}

$array = array(1,2.4,3.6);
print_r(Product($array));
?>

Output :

8.64

array_product() Array elements containing string in PHP

When the array given to the array_product() function contains string values, then the array_product() function returns 0 as the string element is considered as 0.

Code Example :

<?php


function Product($array)
{
	$result = array_product($array);
	return($result);
}

$array = array(1,'php',3,4);
print_r(Product($array));
?>

Output :

0

Also if any one of the element is zero in the given array then the product is zero. If any of the value is Boolean False then it is treated as zero.

Conclusion

In this tutorial we learnt about the PHP array_product() Function and the different examples of using it to calculate the array product.

Also Read:

5 ways to Get First Character From a String using JavaScript
How to Convert a String to Boolean in JavaScript