Forcing a type with type casting

PHP will automatically convert data types as necessary across the board - you need not worry about it happening. If you specifically wish to override PHP's type conversion, you can perform what is called a type cast - you forcibly convert a variable of type A to type B. In PHP, type casting looks like this:

    $mystring = "wombat";
    $myinteger = (integer)$mystring

At first, $mystring contains a string. However, we type cast it to be an integer, so PHP will convert it to an integer, and place the result into $myinteger. You can type cast as boolean using (bool), string using (string), and floating-point using (float).

Type casting is most often used to specifically enforce a type in order to provide extra security or just to make sure a set type of data is being used. For example, if your script absolutely requires an integer number, it's a smart move to typecast your variable with (integer) so that PHP will convert any other type to integer or do nothing if the type is already integer. Converting a float to an integer will automatically round the number down, and is actually faster than using the equivalent function.


Want to learn PHP 7?

Hacking with PHP has been fully updated for PHP 7, and is now available as a downloadable PDF. Get over 1200 pages of hands-on PHP learning today!

If this was helpful, please take a moment to tell others about Hacking with PHP by tweeting about it!

Next chapter: Non-decimal number systems >>

Previous chapter: Automatic type conversion

Jump to:


Home: Table of Contents

Copyright ©2015 Paul Hudson. Follow me: @twostraws.