Backend Development 4 min read

Using PHP's array_product() Function to Compute the Product of Array Elements

This article explains PHP's array_product() function, detailing its basic usage, handling of integers, floats, strings, and non-numeric values, and provides multiple code examples illustrating how to calculate the product of array elements in various scenarios.

php中文网 Courses
php中文网 Courses
php中文网 Courses
Using PHP's array_product() Function to Compute the Product of Array Elements

In PHP, the array_product() function calculates the product of all elements in an array and returns the result, returning 1 for an empty array.

Basic usage: the function accepts an array and returns the multiplication of its values.

Example with integers:

$array = array(2, 4, 6);
$result = array_product($array);
echo "The product of the array elements is: " . $result; // outputs 48

Example 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, PHP converts them to numbers before multiplication:

$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 value, the function returns 0:

$array = array(2, 4, "hello");
$result = array_product($array);
echo "The product of the array elements is: " . $result; // outputs 0

Overall, array_product() is a convenient built‑in function for multiplying array elements, working with integers, floats, and numeric strings, while returning 0 when non‑numeric values are present.

backendfunctionsarraysarray_product
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

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