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 Courses
php Courses
php Courses
Using PHP's array_product() Function to Compute the Product of Array Elements

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: 48

The 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.125

When 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: 48

If 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: 0

In 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.

Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

php-functionsarray_productarray-manipulation
php Courses
Written by

php Courses

php中文网's platform for the latest courses and technical articles, helping PHP learners advance quickly.

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.