Home > Backend Development > PHP Tutorial > 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)

藏色散人
Release: 2023-04-05 17:04:01
Original
3031 people have browsed it

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)
Copy after login

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)); 
?>
Copy after login

Output:

24
Copy after login

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));
Copy after login

Output:

0
Copy after login

Code example 3:When the array is empty

<?php 

$a1=array(); 
  
echo(array_product($a1));
Copy after login

Output:

1
Copy after login

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!

Related labels:
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template