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:

(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:

// 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. ;)