by buster · 14y ago · 0 comments
First of all, why does the function even accept strings? There should be some eception happening. Second, why does it return 0, i could understand NULL but not 0 (for a function that is supposed to handle numbers, having it return a number in the invalid case, what is that?)
Why not?
> There should be some eception happening.
PHP's built-in functions do not ever throw exceptions.
> Second, why does it return 0, i could understand NULL but not 0
Well it doesn't anymore, but it used to, and that kind-of made sense in the context of the language being PHP: in PHP (userland), when using a string in a numeric context that string will automatically be converted to a number:
> php -r 'print (1 + "3") . "\n";'
4
when the string can not be parsed to a number (meaning it is not prefixed by something which looks like a number), it's just converted to `0`: > php -r 'print (1 + "whelp") . "\n";'
1
And I expect that is the former behavior of the function: it coerced whatever it got to a number, so an empty or non-numeric string would get converted to the float 0.0, which would then get formatted as usual.The problem with PHP's weak typing is PHP's hit-and-miss implementation. Check out AWK, another weakly typed language, for example:
BEGIN{printf "%5.2f\n", ""}
prints "0.00" as would be reasonable.
Because PHP was invented as a web language to process web forms and generally your inputs always came to you as a string.