PHP Type Casting

Type casting in PHP means converting one data type to another manually. You can cast variables into integer, float, string, boolean, array, object, or null.

Example:
<?php
    $value = "100";

    $intValue = (int)$value;     // Cast to integer
    $floatValue = (float)$value; // Cast to float
    $stringValue = (string)$value; // Cast to string
    $boolValue = (bool)$value;   // Cast to boolean

    echo $intValue;
    echo $floatValue;
    echo $stringValue;
    echo $boolValue;
?>
Other Type Casting Examples:
<?php
    $num = 50;

    $arrayValue = (array)$num;   // Cast to array
    $objectValue = (object)$num; // Cast to object
    $nullValue = (unset)$num;    // Cast to null (deprecated)
?>
Mixed Type Casting:
<?php
    $str = "25.6";

    $toInt = (int)$str;     // 25
    $toFloat = (float)$str; // 25.6
    $toBool = (bool)$str;   // true (non-empty string)
?>

👉 Explanation:

  • Type casting tells PHP to convert a variable into another type.
  • Common cast types: (int), (float), (string), (bool), (array), and (object).
  • Boolean casting: non-empty strings and non-zero numbers become true.
  • String casting: converts numbers or booleans into readable text format.
  • Array casting: wraps the variable inside an array.
PHP Tutorial