Home  >  Article  >  Backend Development  >  How to calculate the product of all values ​​in an array in PHP? (code example)

How to calculate the product of all values ​​in an array in PHP? (code example)

藏色散人
藏色散人Original
2019-03-20 17:30:362981browse

array_product() is a built-in function in PHP that returns the product of all the numbers in a given array. This function accepts an array consisting only of numbers. If there is other data in the array besides numbers, the function returns 0.

How to calculate the product of all values ​​in an array in PHP? (code example)

Syntax:

array_product($array)

Parameters: The function has a mandatory parameter $array, for which the product of all values ​​is calculated.

Return value: This function returns three different values ​​based on the following conditions:

Returns 0 if the array contains at least one non-numeric data.

When an empty array is passed as parameter, it returns 1.

If neither of the above conditions is met, return the product of all items in the array.

Code example 1:

<?php 
$a1=array(1, 2, 3, 4); 
  
echo(array_product($a1)); 
?>

Output:

24

Code example 2: When the array contains at least one When non-numeric data:

<?php 

$a1=array(1, 2, 3, &#39;a&#39;); 
  
echo(array_product($a1));

Output:

0

Code example 3:When the array is empty

<?php 

$a1=array(); 
  
echo(array_product($a1));

Output:

1

Related recommendations: "PHP Tutorial"

This article is an introduction to the method of calculating the product of all values ​​in an array in PHP. I hope it will be helpful to friends in need!

The above is the detailed content of How to calculate the product of all values ​​in an array in PHP? (code example). For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn