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.

    filter_none

    edit
    close

    play_arrow

    link
    brightness_4
    code

    <?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));
    ?>

    chevron_right

    
    

    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.

    filter_none

    edit
    close

    play_arrow

    link
    brightness_4
    code

    <?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));
    ?>

    chevron_right

    
    

    Output:

    694.7426304
    

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



My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.




Article Tags :
Practice Tags :


Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.