Join the social network of Tech Nerds, increase skill rank, get work, manage projects...
 
  • Calculate sum and product of all values in the array

    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 121
    Comment on it

    Many times we need to calculate sum or product of values stored in an array. The most common way is to calculate sum or product by using for or foreach loop. For example we have an array with some numeric values, now we want to calculate the total sum and total product of these values.

    <?php
    $arr = array(2, 3, 7, 10);
    $sum = 0; 
    $product = 1; 
    foreach($arr as $val){
     $sum += $val;
     $product *= $val;
    }
    echo "Total Sum : ".$sum;
    echo "Total Product : ".$product;
    ?>
    

    Output :
    Total Sum : 22
    Total Product : 420


    In PHP there are two built in functions to calculate sum and product of array values.


    1. array_sum() : array_sum() calculate the total sum of array values and returns the sum as integer or float value.

    Syntax : array_sum(array)


    Description :
    array : Specifies an array. (Required)


    Example :

    <?php
    $arr = array(2, 3, 7, 10);
    echo "Total Sum : ".array_sum($arr);
    ?>
    

    Output : 22


    2. array_product() : Just like array_sum(), array_product() calculate the product of array values and returns the product as integer or float value.

    Syntax : array_product(array)


    Description :
    array : Specifies array.(Required)


    Note :

    • From PHP version 5.3, array_product() return 1 for empty array.
    • For previous version, array_product() return 0 for empty array.

    Example :

    <?php
    $arr = array(2, 3, 7, 10);
    echo "Product : ".array_product($arr);
    ?>
    

    Output : 420


    Important : Above functions can not be used directly to calculate sum and product for multi-dimensional array.


 0 Comment(s)

Sign In
                           OR                           
                           OR                           
Register

Sign up using

                           OR                           
Forgot Password
Fill out the form below and instructions to reset your password will be emailed to you:
Reset Password
Fill out the form below and reset your password: