Is there any difference between typecasting and using a function to convert a variable to some type?
(float)$var
VS. floatval($var)
If there are, when one of those should be used instead of the other?
PHP settype() Function The settype() function converts a variable to a specific type.
Explicit Type Casting Mainly in type casting can be done with these data type function: Int() : Int() function take float or string as an argument and return int type object. float() : float() function take int or string as an argument and return float type object.
To convert string to integer using PHP built-in function, intval(), provide the string as argument to the function. The function will return the integer value corresponding to the string content. $int_value = intval( $string );
There's no difference in the resulting value, just:
(float)
is a language feature and very quickfloatval()
incurs the overhead of a function call (minimal, but nonetheless...)floatval()
as a function can be used in ways that (float)
cannot, e.g. array_map('floatval', $foo)
The last point is, I believe, the main reason for floatval
's existence: so each casting operation has a function equivalent, which can be useful in some circumstances.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With