PHP array_product() Function

PHP array_product()  function is “used to calculate the product of all elements in an array.” This function multiplies all the values in the array together and returns the result.

Syntax

array_product($array)

Parameters

$array: It refers to the input array.

Return value

It returns the product of all the values as an integer or a float.

Visual RepresentationVisual Representation of PHP array_product() Function

Example 1: How to Use array_product() function

<?php
 
$arr = [1, 3, 5, 7, 9]; 

$result = array_product($arr);

echo $result;

Output

945

Example 2: Pass the float valuesVisual Representation of Pass the float values

<?php
 
$arr = [1.1, 2.1, 3.3, 4.7, 5.6]; 

$result = array_product($arr);

echo $result;

Output

200.63736

Example 3: Array Elements Containing StringVisual Representation of Array Elements Containing StringIf any element in the input array is the string, the function will type-case it to 0.  That is why it will always return 0 in such a case.

<?php
 
$arr = [1, 3, 5, 'Eleven', 9]; 

$result = array_product($arr);

echo $result;

Output

0

Example 4: Passing empty ArrayVisual Representation of Passing empty Array

 

As of PHP 5.3.6, the product of an empty array is 1. Before PHP 5.3.6, this function would return 0 for an empty array.

<?php
 
$arr = []; 

$result = array_product($arr);

echo $result;

Output

1

That’s it.

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.