Advertisement

Google Ad Slot: content-top

PHP Casting

~1 min read · PHP
On this page

Type casting refers to converting a value from one data type to another.


There are two types of casting in PHP:


  1. Explicit casting
  2. Implicit casting (type juggling)

Explicit Casting


Explicit casting is done when you want to manually convert a variable from one type to another using explicit type casts.


Supported Data Types for Casting


  • (int) or (integer): Converts to an integer.
  • (bool) or (boolean): Converts to a boolean (0 becomes false, anything else becomes true).
  • (float), (double), or (real): Converts to a float.
  • (string): Converts to a string.
  • (array): Converts to an array.
  • (object): Converts to an object.
  • (unset): Converts to data type NULL


1) Cast to Integer


When casting a float or string to an integer, the fractional part is removed (truncated), or if the string contains non-numeric characters, it will be converted to 0.

Example
   
Try it yourself

2) Cast to Boolean


To cast to boolean, use the (bool) statement:

Example
   
Try it yourself

3) Cast to Float


When casting to a float, the value is treated as a decimal number.

Example
   
Try it yourself

4) Cast to String


You can cast integers, floats, or booleans to strings.

Example
   
Try it yourself

5) Type Casting in Arrays


PHP will not cast arrays to another data type unless you manually handle it with explicit casting.

Example
   
Try it yourself

Objects converts into associative arrays where the property names becomes the keys and the property values becomes the values.

Example
  
Try it yourself

6) Type Casting in Objects


To cast to object, use the (object) statement.

Example
   
Try it yourself

Indexed arrays converts into objects with the index number as property name and the value as property value.


Associative arrays converts into objects with the keys as property names and values as property values.

Example
  "35", "Ben"=>"37", "Joe"=>"43"); // associative array
    
    $a = (object) $a;
    $b = (object) $b;
    
    var_dump($a);
    var_dump($b);
  ?> 
Try it yourself

7) Cast to NULL


To cast to NULL, use the (unset) statement:

Warning

This feature has been DEPRECATED as of PHP 7.2.0, and REMOVED as of PHP 8.0.0. Relying on this feature is highly discouraged.

Example
   
Try it yourself

Implicit Casting


Implicit casting happens automatically, such as when combining a string with a number.

Example
  ";  // Outputs: "The number is 10"
    var_dump ($text)
  ?> 
Try it yourself