Add numbers of several Strings in PHP

-3

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

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

I want to get the result of 66 + 5 = 71.

    
asked by anonymous 09.09.2018 / 14:31

1 answer

0

Hello,

You can do the sum as follows.

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

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

I recommend in this case to use PHP math functions: bcadd

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

Here's an article in English explaining the problem: php-floating-point-numbers- when-equating

    
10.09.2018 / 04:05