skip to Main Content

How to add all values in this array?

If the value with the scientific notation 4.400...E+26 is commented out the result is 10171018899000

$list = [
    700,
    700,
    200,
    700,
    2853300,
    595300,
    4736700,
    1700,
    4.4002258020009E+26,
    200,
    39800,
    171002250300,
    8410600,
    100,
    1000,
    10000000000800,
    100,
    6000,
    700,
    100
];
print_r($list);
$sum = array_sum($list);
echo "sum: $sumn";
$sum = (int)$sum;
echo "sum: $sumn";

output

sum: 4.400225802001E+26
sum: -2402111299539435520

2

Answers


  1. You could use utilize bcmath for large numbers and high preceision calculation. With the help of sprintf you can easily convert the notation to a string. Instead of array sum, we can use a reducer.

    Demo: https://3v4l.org/ddJM9

    echo array_reduce($list, fn($carry, $item) => bcadd($carry, sprintf('%.f', $item)), '0');
    
    440022580200100168512040504
    
    Login or Signup to reply.
  2. The result you’re getting is not "completely wrong." It’s in scientific notation. The number 4.4002258020009E+26 is a very large number that is expressed in scientific notation (also known as exponential notation) for conciseness.

    In scientific notation, 4.4002258020009E+26 is equivalent to 4.4002258020009 * 10^26, which is an incredibly large number.

    When you’re printing the sum, PHP is using scientific notation for the output because it’s a convenient way to represent extremely large numbers.

    If you want to see the result in standard decimal notation, you can use number_format() to format the output:

    $list = [
        700,
        700,
        200,
        700,
        2853300,
        595300,
        4736700,
        1700,
        4.4002258020009E+26,
        200,
        39800,
        171002250300,
        8410600,
        100,
        1000,
        10000000000800,
        100,
        6000,
        700,
        100
    ];
    
    $sum = array_sum($list);
    // Format as integer with comma as thousands separator
    $formatted_sum = number_format($sum, 0, '.', ','); 
    $formatted_sum_without_comma = number_format($sum, 0, '.', ''); 
    
    echo "Sum: $formatted_sum";
    //Result: Sum: 44,002,258,020,009,299,302,508,000
    
    echo '<br>';
    
    echo "Sum: $formatted_sum_without_comma ";
    //Result: Sum: 44002258020009299302508000
    

    This will give you the sum in a more human-readable format. Also if the sum is still too large, you may encounter limitations in PHP’s floating-point precision.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search