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

<?php $a = 5; // Integer $b = "10"; // String $c = "Hello"; // String // PHP juggles the string '10' into an integer for arithmetic echo "Result 1: " . ($a + $b); // Output: 15 // When performing arithmetic on non-numeric strings, PHP treats them as 0 echo "<br>Result 2: " . ($a + $c); // Output: 5 (5 + 0) // Comparison Juggling (Dangerous!) if (0 == "hello") { echo "<br>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

<?php $num_str = "45.99"; $integer_val = (int) $num_str; echo "Integer: " . $integer_val; // Output: 45 $float_val = (float) $integer_val; echo "<br>Float: " . $float_val; // Output: 45.0 ?>