Back to course

Type Juggling and Type Casting

PHP: The Complete 0 to Hero Bootcamp

8. Type Juggling and Type Casting

PHP is a loosely typed language, meaning it doesn't require explicit type declarations and often automatically converts (juggles) types when necessary.

Type Juggling (Automatic Conversion)

When PHP encounters an operator that expects a certain type, it attempts to convert the operands.

php

Result 2: " . ($a + $c); // Output: 5 (5 + 0) // Comparison Juggling (Dangerous!) if (0 == "hello") { echo "
They are loosely equal!"; // Output: They are loosely equal! } // Why? PHP converts 'hello' to an integer 0 for comparison. ?>

Type Casting (Explicit Conversion)

To avoid unexpected juggling, you can explicitly cast a variable to a different type using parentheses and the desired type name.

CastDescription
(int) or (integer)Casts to Integer
(float) or (double)Casts to Float
(string)Casts to String
(bool) or (boolean)Casts to Boolean

php

Float: " . $float_val; // Output: 45.0 ?>