PHP Casting

In PHP, casting is the process of converting a variable from one data type to another. PHP is a loosely typed language, so it often does type juggling automatically, but you can also explicitly cast variables.

Syntax

$castedVariable = (targetType) $originalVariable;

Common Casts in PHP

Type Cast Description Example
(int) or (integer) Cast to integer $a = (int) "123";
(bool) or (boolean) Cast to boolean $a = (bool) 1;
(float) or (double) or (real) Cast to float $a = (float) "12.3";
(string) Cast to string $a = (string) 123;
(array) Cast to array $a = (array) "value";
(object) Cast to object $a = (object) $array;
(unset) Cast to NULL (rarely used) $a = (unset) $value;

Examples

$val = "10"; // Cast to integer $intVal = (int) $val; // 10 // Cast to float $floatVal = (float) $val; // 10.0 // Cast to boolean $boolVal = (bool) $val; // true // Cast to string $strVal = (string) 123; // "123" // Cast to array $arrayVal = (array) $val; // [0 => "10"] // Cast to object $objectVal = (object) $val; // stdClass Object with scalar value as property

Notes

  • PHP automatically casts types in many situations (e.g., in arithmetic or comparisons).

  • Use explicit casting when you need to be certain about the data type.