Ad space (banner)
๐Ÿ˜PHP Lessons
Lesson 18 / 68

Logical Operators (AND, OR, NOT)

In this lesson you will get comfortable with PHP's logical operators so you can combine several conditions in one decision. This is for anyone searching for "PHP logical operators how to use".

When you want to combine conditions you use logical operators. && means "both are true", || means "at least one is true", and ! means "the opposite". They are indispensable for tests such as "18 or over and holding a ticket".

The sample code checks "18 or over and holding a ticket" with $age >= 18 && $hasTicket, and "under 18, or not holding a ticket" with $age < 18 || !$hasTicket. Notice how a ternary operator prints the result.

A common stumbling block for beginners is mixing up && and ||. Saying the condition out loud in plain English first - "both" or "either" - before turning it into code makes mistakes far less likely.

Short-circuit evaluation is worth knowing too: if the left side of && is false, the right side is never evaluated. Keeping that in mind makes conditions that call functions more efficient.

๐Ÿ“– Reference code
โœ๏ธ Your code
Type your code, then press "Run"

๐Ÿงช This site can't compile or run PHP directly, so it checks on the spot whether what you typed matches the reference code (scoring happens entirely in your browser โ€” nothing is sent anywhere).

Ad space (banner)
Ad space (in-article)