CGPA Calculator Hash Generator Bcrypt Hasher Tree Visualizer Barcode Generator Engineering Blog Editorial Standards All Tools Games HTML5 JavaScript PHP MySQL

PHP Type Casting

Type casting is the process of explicitly converting a variable from one data type to another. Since PHP is loosely typed, it often does this automatically, but there are times when you need to force a specific type for security or calculation reasons.


How to Cast

To cast a variable, you place the name of the desired data type in parentheses before the variable you want to convert.

<?php
    $x = 5; // Integer
    $x = (string) $x; // Now $x is a String "5"
    var_dump($x);
?>

Supported Casting Operators

PHP recognizes the following operators for explicit casting:

Operator Converts to
(string) String
(int) / (integer) Integer
(float) / (double) Float
(bool) / (boolean) Boolean
(array) Array
(object) Object

Practical Examples

Float to Integer

Casting a float to an integer will always **truncate** the decimal part (it does NOT round to the nearest number).

<?php
    $num = 45.89;
    echo (int)$num; // Outputs: 45
?>

Array to Object

Converting an array to an object turns the array keys into object properties. This is very common when working with JSON data.

<?php
    $userArray = ["name" => "John", "age" => 25];
    $userObj = (object)$userArray;
    
    echo $userObj->name; // Outputs: John
?>
Safety Note: Casting to (bool) follows the same rules as truthy/falsy values. For example, (bool)0 is false, while (bool)1 is true.

The settype() Function

An alternative to parentheses casting is the settype() function. Unlike parentheses casting (which returns a new value), settype() modifies the original variable.

<?php
    $val = "100 apples";
    settype($val, "integer");
    echo $val; // Outputs: 100
?>
Pro Tip: Casting is extremely useful when receiving data from an HTML form (where everything is sent as a string). Casting a numerical input to (int) ensures your math works correctly.

Key Points to Remember

  • Type casting is explicit conversion using parentheses like (int).
  • Casting a float to an integer removes decimals without rounding.
  • You can convert Arrays to Objects to use arrow syntax (->).
  • Parentheses casting returns a new value; **settype()** changes the variable.
  • Casting is a standard security practice to ensure input data matches the expected type.