PHP Type Casting
In this page:
What is Type Casting?
Type casting is explicitly telling PHP to treat a value as a different type by writing the target type in parentheses before it, like (int) $value. It's a deliberate, visible conversion — unlike PHP's automatic type juggling, which happens silently whenever an operator needs operands of matching types.
Example: What is Type Casting?
<?php
$value = "42";
$intValue = (int) $value;
var_dump($intValue);
?>
Login to try C/C++/Java/PHP code in the editor
Casting to Integer and Float
(int) truncates toward zero rather than rounding — (int) 9.9 gives 9, not 10 — and stops reading a string at the first non-numeric character, so (int) "42abc" is 42. (float) follows the same leading-numeric-prefix rule but preserves the decimal portion.
Example: Casting to Integer and Float
<?php
echo (int) 9.9 . "\n";
echo (int) "42abc" . "\n";
echo (float) "3.14xyz";
?>
Login to try C/C++/Java/PHP code in the editor
Casting to String and Boolean
(string) converts numbers and booleans into their textual form (true becomes "1", false becomes ""), which matters because PHP does this automatically during concatenation anyway. (bool) treats 0, 0.0, "", "0", empty arrays, and null as false — everything else, including the string "0.0", counts as true.
Example: Casting to String and Boolean
<?php
var_dump((string) true);
var_dump((string) false);
var_dump((bool) "0.0");
var_dump((bool) "");
?>
Login to try C/C++/Java/PHP code in the editor
Casting to Array and Object
(array) wraps a scalar in a single-element array, or converts an object's public properties into key-value pairs. (object) does the reverse for an associative array, turning each key into a dynamic property — useful when an API expects stdClass objects instead of plain arrays.
Example: Casting to Array and Object
<?php
$arr = (array) "hello";
print_r($arr);
$obj = (object) ["name" => "Alice"];
echo $obj->name;
?>
Login to try C/C++/Java/PHP code in the editor
Casting vs Automatic Type Juggling
PHP silently coerces types during comparisons and arithmetic ("5" + 3 becomes 8), which is convenient but can produce surprising results with loosely-typed data from user input. Explicit casting makes the conversion visible in the code and is the safer choice whenever a value's type is uncertain.
Example: Casting vs Automatic Type Juggling
<?php
echo "5" + 3; // automatic juggling
echo "\n";
echo (int) "5" + 3; // explicit casting
?>
Login to try C/C++/Java/PHP code in the editor
Chapter Quiz — Complete all 13 topics to unlock
0/13 topics done
Complete these topics first: