Using PHP's array_product() Function to Compute the Product of Array Elements
This article explains how PHP's array_product() function calculates the product of all elements in an array, covering usage with integers, floats, strings, and handling of non‑numeric values, and provides multiple code examples illustrating each case.
PHP provides many powerful functions for array handling, and one useful function is array_product() , which calculates the product of all elements in an array and returns the result.
The basic usage of array_product() accepts an array as a parameter and returns the product of its elements; if the array is empty, it returns 1.
Example with integers:
$array = array(2, 4, 6);
$result = array_product($array);
echo "The product of the array elements is: " . $result; // outputs: 48The function also works with floating‑point numbers:
$array = array(1.5, 2.5, 3.5);
$result = array_product($array);
echo "The product of the array elements is: " . $result; // outputs: 13.125When the array contains numeric strings, array_product() converts them to numbers before calculation:
$array = array("2", "4", "6");
$result = array_product($array);
echo "The product of the array elements is: " . $result; // outputs: 48If the array includes a non‑numeric element, the function returns 0:
$array = array(2, 4, "hello");
$result = array_product($array);
echo "The product of the array elements is: " . $result; // outputs: 0In summary, array_product() is a convenient PHP function that can compute the product of array elements regardless of whether they are integers, floats, or numeric strings, but it returns 0 when any element cannot be converted to a number.
In practical development, you can use array_product() to calculate totals such as product prices or any numeric dataset where a multiplicative aggregate is needed.
php中文网 Courses
php中文网's platform for the latest courses and technical articles, helping PHP learners advance quickly.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.