Add numbers from multiple Strings in PHP

Asked

Viewed 637 times

-3

How do I add the numbers of several Strings in PHP, for example:

string(2) "66" string(1) "5"

I wish to obtain the result of 66 + 5 = 71.

  • 2

    With the operator + or array_sum

1 answer

0

Hello,

You can make the sum as follows.

<?php
$a = '66';
$b = '5';
$soma = $a + $b;
echo $soma;
//exibe 71
?>

Now, if you intend to add decimal numbers, the story is different.

I recommend in this case using PHP mathematical functions: bcadd

<?php
echo PHP_EOL;
$a = '0.66';
$b = '0.05';
$soma = bcadd($a, $b, 2);
echo $soma;
//exibe 0.71
?>

Here is an article in English explaining the problem: don-t-trust-php-floating-point-Numbers-when-equating

Browser other questions tagged

You are not signed in. Login or sign up in order to post.