Tutorialspoint.dev

PHP | array_product() Function

There are some point of time when we need to calculate the product of all elements in an array. The most basic way to do this is to iterate over all elements and calculate the product but PHP serves us with a builtin function to do this. The array_product() is a built-in function in PHP and is used to find the products of all the elements in an array.

Syntax:

array_product($array)

Parameters: The function takes only one parameter $array, that refers to the input array whose products of elements we wish to get.

Return Value: The array_product() function returns an integer or float value depending on the nature of elements of the array.

Examples:



Input : array = (5, 8, 9, 2, 1, 3, 6)
Output : 12960

Input : array = (3.2, 4.8, 9.1, 4.36, 1.14)
Output : 694.7426304

Below programs illustrates the working of array_product() function:

  • When the array passed to the array_product() function contains only integral values then the array_product() function returns an integer value equals to the product of all the elements of the array passed to it.

    <?php
      
    // PHP function to illustrate the use 
    // of array_product()
      
    // Return Integer number
    function Product($array)
    {
        $result = array_product($array);
        return($result);
    }
      
    $array = array(5, 8, 9, 2, 1, 3, 6);
    print_r(Product($array));
    ?>

    Output:

    12960
    
  • When the 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
    // PHP function to illustrate the use of
    // array_product()
    function Product($array)
    {
        $result = array_product($array);
        return($result);
    }
      
    $array = array(3.2, 4.8, 9.1, 4.36, 1.14);
    print_r(Product($array));
    ?>

    Output:

    694.7426304
    

Reference:
http://php.net/manual/en/function.array-product.php



This article is attributed to GeeksforGeeks.org

You Might Also Like

leave a comment

code

0 Comments

load comments

Subscribe to Our Newsletter