PHP Tip #4: Type Casting

/ PHP / by Paul Robinson / 5 Comments
This post was published back on March 18, 2009 and may be outdated. Please use caution when following older tutorials or using older code. After reading be sure to check for newer procedures or updates to code.

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:

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:

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

Author’s gravatar

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**.

Reply
Author’s gravatar

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. 🙁

Reply
Author’s gravatar

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.

Reply
Older Comments
Newer Comments

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.

I'll keep your WordPress site up-to-date and working to its best.

Find out more