I was wondering what is the best way to typecast a value from one type to another.
Which variant should we use:
intval($value);
settype($value, 'int')
(int)$value
All of them produce same result.
Answer: Use the strval() Function You can simply use type casting or the strval() function to convert an integer to a string in PHP.
Contrary to C, C++ and Java, type of PHP variable is decided by the value assigned to it, and not other way around. Further, a variable when assigned value of different type, its type too changes. This approach of PHP to deal with dynamically changing value of variable is called type juggling.
A typecast example is the transformation of an integer into a string. This could be used to compare two numbers if one is stored as a string and the other is an integer. If compatible, Java must automatically perform a conversion called Automatic Type Conversion and, if not, it must be specifically cast or converted.
PHP settype() Function The settype() function converts a variable to a specific type.
(int)$value
saves one function call compares to intval($value)
and settype($value, 'int')
.
And (int)$value
is clean enough, so I prefer this way.
When you need to use intval($value)
is that when you need to use the specified base for the conversion (the default is base 10). intval accepts a second parameter for the base for the conversion.
I prefer using
settype($value,getType(intval((int)$value)));
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