Home >Backend Development >PHP Tutorial >PHP method to calculate the sum and product of values ​​in an array and example analysis

PHP method to calculate the sum and product of values ​​in an array and example analysis

墨辰丷
墨辰丷Original
2018-06-04 10:45:311686browse

This article mainly introduces the method of calculating the sum and product of values ​​in an array in PHP. It analyzes the functions and usage of array_sum and array_product functions in detail in the form of examples. Friends in need can refer to it

·1. Overview:

array_sum() function is used to calculate the sum of all values ​​in an array.
array_product() function is used to calculate the product of all values ​​in an array.

2. Usage example:

array_sum()

PHP array_sum() function is used to calculate all values ​​in the array The sum of , returns the calculation result as an integer or floating point number, and non-numeric units will be treated as 0.

Grammar:

number array_sum( array array )

Example:

<?php
$arr_a = array(1, 2, 3, "a");
echo array_sum($arr_a);  //输出:6
?>

array_product()

PHP array_product() function is used to calculate the product of all values ​​in the array, and returns the calculation result as an integer or floating point number. Non-numeric cells will be treated as 0.

Grammar:

number array_product( array array )

Example:

<?php
$arr_a = array(1, 2, 3);
echo array_product($arr_a);  //输出:6
$arr_b = array(1, 2, 3, "abc");
echo array_product($arr_b);  //输出:0
?>

Summary: The above is the entire content of this article, I hope it will be helpful to everyone's study.

Related recommendations:

phpDetailed explanation of the configuration method of using pdo to connect to sqlite3

phpImplementing the method of determining the format through the file header

phpUsage and example analysis of time function

The above is the detailed content of PHP method to calculate the sum and product of values ​​in an array and example analysis. 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