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.
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 48Example 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, 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 48If 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 0Overall, 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.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
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.
