← Back to PHP Course | Chapter 1: Introduction & Basics | Lesson 12 of 13

PHP Type Casting

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
<?php
$value = "42";
$intValue = (int) $value;
var_dump($intValue);
?>

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
<?php
echo (int) 9.9 . "\n";
echo (int) "42abc" . "\n";
echo (float) "3.14xyz";
?>

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
<?php
var_dump((string) true);
var_dump((string) false);
var_dump((bool) "0.0");
var_dump((bool) "");
?>

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
<?php
$arr = (array) "hello";
print_r($arr);
$obj = (object) ["name" => "Alice"];
echo $obj->name;
?>

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
<?php
echo "5" + 3; // automatic juggling
echo "\n";
echo (int) "5" + 3; // explicit casting
?>

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.