Avatar ·

What is the difference between the comparison operators == (loose equality) and === (strict equality) in PHP?

Hello everyone! I just started learning PHP and encountered a confusing situation. I'm writing a simple script to check a user's age, and the results are puzzling me.

\n\n

Here's my code:

\n\n
<?php\n$age = "25";  // string\n$legal_age = 25;  // number\n\nif ($age == $legal_age) {\n    echo "Age matches (==)";  // this is output\n}\n\nif ($age === $legal_age) {\n    echo "Age matches (===)";  // this is NOT output\n}\n?>
\n\n

Why does the first if trigger, but the second one doesn't? Both values seem the same — 25. I read in the manual that there are == and ===, but the difference isn't obvious to me. When should I use each operator? And what happens if I accidentally mix them up in a real project? For example, when checking a password or an ID from a database?

\n\n

Thanks in advance.