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?
A. Error
B. 42
D. 42abc
💡 Casting a string to int takes the leading numeric portion: 42.
2. What does (bool)"" return?
A. true
B. null
C. false
💡 An empty string cast to bool is false.
3. What is "type juggling"?
A. Explicit casting
B. PHP automatically converting types based on context
C. A PHP 8 feature
D. A strict type mode
💡 Type juggling is PHP automatically converting types in expressions.
4. Which function returns the type of a variable as a string?
A. type()
B. typeOf()
C. gettype()
D. vartype()
💡 gettype() returns a string like "integer", "string", "array", etc.
5. What does (array)"hello" produce?
A. Error
B. ["h","e","l","l","o"]
C. ["hello"]
D. null
💡 Casting a non-array scalar to array wraps it in a single-element array.
Submit answers