PHP Type Casting

What is Type Casting?

Type casting means converting one data type to another. PHP automatically casts types in many cases (type juggling), but you can also cast explicitly.

Explicit Casting Syntax

Place the desired type in parentheses before a variable or value:

$x = 10.5;
$y = (int) $x;     // $y is 10

$z = (string) true; // $z is "1"
  • (int) or (integer)
  • (float) or (double) or (real)
  • (string)
  • (bool) or (boolean)
  • (array), (object), (unset)

Casting Examples

$a = "123abc";
$b = (int) $a;     // 123

$x = (bool) 0;     // false
$y = (bool) "Hi"; // true

$arr = (array) "hello";  // array with one element
$obj = (object) ["x" => 10];

Useful Conversion Functions

  • strval()
  • intval()
  • floatval()
  • boolval()
  • settype() (modifies in place)
$num = "42";
$intVal = intval($num); // 42

$str = strval(3.14);    // "3.14"

$val = 10;
settype($val, "string");

Automatic Type Conversion (Type Juggling)

PHP automatically converts types in certain operations:

$result = "10" + 5;  // result is 15

This is convenient but can lead to bugs — use explicit casting when in doubt.

Need Help?

Ask the AI if you need help understanding or want to dive deeper in any topic