What is type juggling and strict_types in PHP?

Type juggling means PHP converts the data type of a value automatically when needed. For example, the string "10" is treated as a number when you compare or add it with a number.

<?php
var_dump("10" == 10);    // string and number, values are same
var_dump("abc" == 0);    // false in PHP 8 (it was true in PHP 7)
var_dump(0 == "");       // false in PHP 8 (it was true in PHP 7)
?>

Output:

Output in PHP 8

bool(true)
bool(false)
bool(false)

This automatic change can create bugs. You can ask PHP to be strict with declare(strict_types=1). It must be the first statement of the file, and it affects the function calls made from that file.

<?php
declare(strict_types=1);

function add(int $a, int $b) {
    return $a + $b;
}

echo add(2, 3);        // 5
// echo add("2", "3"); // TypeError, because strings are not accepted
?>

Output:

Tutorials Class - Output Window

5

To be safe, compare with === and use type declarations in functions. See == vs ===.


Learn more about the similar topics:
Tutorials
No Content Found.
Exercises & Assignments
No Content Found.
Interview Questions & Answers
No Content Found.