📡 You're offline — showing cached content
New version available!
Quick Access
Tutorials PHP for Beginners Type Juggling and Casting

Type Juggling and Casting

5 min read Quiz at the end
PHP automatically converts types in operations, which is called type juggling. Adding a number and a string can give unexpected results. Always use === instead of == to compare both value and type safely.

Type Juggling and Casting

PHP automatically converts types (juggling) but you can also cast explicitly.

// PHP type juggling
var_dump(0 == "foo");    // true in PHP 7 (false in PHP 8!)
var_dump("1" == 1);      // true
var_dump("01" == "1");   // true

// Explicit casting
$str  = "42abc";
$int  = (int) $str;      // 42
$float= (float)"3.14px"; // 3.14
$bool = (bool) "";       // false
$arr  = (array) "hello"; // ["hello"]
$str2 = (string) true;   // "1"

// settype()
$var = "123";
settype($var, "integer");
echo gettype($var);  // integer
Topic Quiz · 5 questions

Test your understanding before moving on

1. What does (int)"42abc" return?
💡 Casting a string to int takes the leading numeric portion: 42.
2. What does (bool)"" return?
💡 An empty string cast to bool is false.
3. What is "type juggling"?
💡 Type juggling is PHP automatically converting types in expressions.
4. Which function returns the type of a variable as a string?
💡 gettype() returns a string like "integer", "string", "array", etc.
5. What does (array)"hello" produce?
💡 Casting a non-array scalar to array wraps it in a single-element array.