PHP array_product: The Complete Guide

0
27
PHP Array Product Example | PHP array_product() Function

PHP array_product() is an inbuilt function and is used to find the products of all the items in the array.

PHP array_product()

PHP array_product() is an inbuilt function that calculates and returns the product of an array. The array_product() can be used to test if all values in an array of booleans are TRUE.  

Syntax

See the following syntax.

array_product(array)

See the following code example.

<?php
  
$arr = array(11, 18, 19, 21, 29); 

$product = array_product($arr);

echo $product;

See the output.

➜  pro php app.php
2291058                                                                         
➜  pro

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.

When an array passed to the array_product() function contains both integral and float values then the array_product() function returns a floating-point value equals to the product of all the elements of the array passed to it.

<?php
  
$arr = array(1.1, 2.1); 

$product = array_product($arr);

echo $product;

See the output.

➜  pro php app.php
2.31                                                                            
➜  pro

Elements with 0 in array_product()

If any value in an array is 0, then the function will always return 0.

<?php
  
$arr = array(11, 21, 19, 0, 46, 29); 

$product = array_product($arr);

echo $product;

See the output.

➜  pro php app.php
0                                                                               
➜  pro

Array Elements Containing String

If any item 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 = array(11, 21, 19, 'Eleven', 46, 29); 

$product = array_product($arr);

echo $product;

See the output.

➜  pro php app.php
0                                                                              
➜  pro

Check if all the values are boolean true or not

You can use a function to check whether all the values are true or not.

See the code.

<?php
  
$arr = array(1, 11, 0, true); 

$product = array_product($arr);

echo $product;

See the output.

➜  pro php app.php
0                                                                               
➜  pro

There is one major difference between using the array_product function and boolean operators.

The former returns the integer 0 value and the later returns a bool(false).

Finally, PHP array_product() Function is over.

Recommended Posts

How to Convert PHP Object to Associative Array in PHP

PHP unset()

PHP reverse array

PHP ksort

PHP sort

Leave A Reply

Please enter your comment!
Please enter your name here

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