PHP Tip #4: Type Casting
I kinda touched on Type Casting in the second PHP tip about is_numeric()
. The basic idea is that you can force a variable’s value to another type. For instance, changing a string to an integer.
Well What Use Is Type Casting
So you might be asking what use that is. Well the most common use is to replace is_numeric()
. For example you require a integer instead of a numeric string you can just do this:
1 |
(int) $var = $_GET['input']; |
As shown in the second PHP tip you can expand this to check for converted strings instead of numeric strings since they will always return 0. Another useful use for type casting is to convert the numeric string "1"
& "0"
to their boolean counterparts like this:
1 2 3 |
// Somewhere in the code $var is set to the string "0"; if((bool) $var === true) //Do whatever |
Of course since the string "0"
is already considered false it’s not really necessary, but it can come in handy when you need to do a value & type test (===
) rather than a normal value test. Another handy type cast is the (unset)
cast which will unset the variable it is used on. Think of it as an inline version of unset()
. You can find a full list of all the type casts at php.net.
I hope that’s been of some help to someone. If you have anything to add, such as a better example of type casting cos mine suck, then please feel free to leave a comment. 😉
5 Comments
php.freelancer.mumbai
Hey nice post,
Well I would like to add something which is really very important while working on floats.
Float data type is not capable of representing numbers in the way you expect it to. Just look at following example code, its **output is 7 and not 8**.
php.freelancer.mumbai
This is the php code. pre tag not working in my comment..!!!
php.freelancer.mumbai
Veneficus Unus
Hi,
thanks for the tips, but your code didn’t come out in WP properly. I’ve no idea why since it looks like you used the correct tags. Please try commenting again but just write the code & I’ll try & sort it out. I wish the devs of WP would sort that problem out, it’s really annoying. 🙁
Veneficus Unus
Ahh thanks. It’s just WordPress being a pain in the ass. It happens sometimes. 🙁
For some reason it’s just that sum. If you try
echo (int) ((0.1 + 0.8) *10);
you get the correct answer (9). It is only the sum you gave that gives the wrong answer when being typecast to an integer. I have tried loads of different float to integer conversions & it is definitely only that sum. Very bizzare. Thanks for the info though.