Type casting means converting one data type to another. PHP automatically casts types in many cases (type juggling), but you can also cast explicitly.
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)$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];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");PHP automatically converts types in certain operations:
$result = "10" + 5; // result is 15This is convenient but can lead to bugs — use explicit casting when in doubt.
Ask the AI if you need help understanding or want to dive deeper in any topic