AppDividend
Latest Code Tutorials

PHP Array Product Example | PHP array_product() Function

0

PHP Array Product Example | PHP array_product() Function is today’s topic. The array_product() function calculates and returns the product of an array. The function can be used to test if all values in an array of booleans are TRUE.  The array_product() is the built-in function and is used to find the products of all the items in the array.

PHP Array Product

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 Example | PHP array_product() Function is over.

Recommended Posts

How To Convert PHP Object To Associative Array In PHP

Unset() Function In PHP Tutorial

How To Reverse Array In PHP

How To Sort Array By Key

PHP Sorting Arrays Tutorial

Leave A Reply

Your email address will not be published.

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