0

Is it safe to use INT-type variables in BCMath functions in PHP ?

Example:

<?php
$a = 1;
$b = "1";
echo bcadd($a,$b,0);
?>

This seems to work but is it safe to do this ? Or is there for example a risk that PHP can interpret an INT as something else than it's int value (I'm thinking about hexadecimal values etc) ?

Thanks !

abc
  • 125
  • 4
  • 1
    Your subject line does not match your actual question... – MonkeyZeus Mar 13 '18 at 16:40
  • If you prefer so, you can cast your variables like so: bcadd((int) $a, (int) $b, 0); – Rod Elias Mar 13 '18 at 16:45
  • Rod Elias: I know that, but my question is whether correct results are guaranteed when passing on INTs (either through an INT var or through casting a non INT var) as opposed to STRINGS. – abc Mar 13 '18 at 16:47
  • 1
    bc functions take _string_ arguments and return _strings_. – AbraCadaver Mar 13 '18 at 16:47
  • AbraCadaver: sure, so what errors are to be expected when passing on INTs ? Can you provide a testcase where the result is wrong when passing on non-string arguments ? I know that the result is always a string. – abc Mar 13 '18 at 16:49
  • MonkeyZeus: looks like I can't change it :(. Maybe you can thx to your cazzilion respect points ;) ? – abc Mar 13 '18 at 16:52
  • 1
    If you pass a valid PHP integer (or float) to `bcadd`, it will work the same as if you had first cast the variable to a string. It "accepts" them in much the same way that any PHP function does - they're just transparently converted using the in-built type-casting logic. – iainn Mar 13 '18 at 16:58

1 Answers1

0

Be careful with very large numbers. If you assign a literal integer > PHP_INT_MAX to a variable, PHP will automatically convert it to a float. I know you specifically asked about ints, and in that case you'd be passing a float, but if you don't know that about the automatic conversion it looks like you're using a large int, so I thought it worth mentioning.

$a = 9223372036854775808;
$b = '1';

var_dump($b);              // float 9.2233720368548E+18
echo bcadd($a, $b, 0);     // echoes 1

Basically, the function does take a string. If you give it something that isn't a string, PHP will automatically convert it to a string if it can, unless you have enabled strict mode.

Don't Panic
  • 41,125
  • 10
  • 61
  • 80
  • Many thanks ! For huge numbers (> PHP_INT_MAX) i do use strings, my actual question was if I needed to convert "normal" INT's to strings as well or not, and you cleared it: it is not required. I can pass on 2 "normal" int's and potentially get a string result which is > PHP_INT_MAX – abc Mar 14 '18 at 14:29