Type Juggling and Type Casting
Understand how PHP automatically converts between types and how to cast manually.
What Is Type Juggling?
Type juggling means PHP automatically converts a value's type when an operator or function requires a different type.
This is convenient but can cause subtle bugs if you don't understand the rules.
Juggling in Arithmetic
PHP converts strings to numbers when used in arithmetic context:
<?php
echo '5' + 3; // 8 — string '5' becomes int 5
echo '5.5' + 1.5; // 7 — string '5.5' becomes float
echo '5 cats' + 1; // 6 — leading numeric part used, rest ignored
echo 'cats' + 1; // 1 — non-numeric string becomes 0All lessons in this course
- Declaring Variables in PHP
- PHP Data Types Overview
- Echo and Print Output
- Type Juggling and Type Casting