Skip to Content
Learn
Logical Operators and Compound Conditions
The && Operator

Often, we’ll encounter situations where we have more than one condition we need satisfied in order to take an action.

The logical && operator returns TRUE only if both of its operands evaluate to TRUE. It returns FALSE if either or both of its operands evaluate to false.

TRUE && TRUE; // Evaluates to: TRUE FALSE && TRUE; // Evaluates to: FALSE TRUE && FALSE; // Evaluates to: FALSE FALSE && FALSE; // Evaluates to: FALSE

Let’s think about a real-world example: when attempting to withdraw money from an ATM, the account holder must both provide the correct PIN and have enough money in their account.

$correct_pin = TRUE; $sufficient_funds = TRUE; if ($correct_pin && $sufficient_funds){ echo "You can make the withdrawal."; }

The && operator has a higher operator precedence than the || operator. This means that in a complex statement that includes both operators, the computer will evaluate the part of the expression with && first:

TRUE || TRUE && FALSE // Evaluates to: TRUE

If we want to control the order in which the expression is evaluated, we can use parentheses for force the order:

(TRUE || TRUE) && FALSE // Evaluates to: FALSE

Let’s get some practice with the && operator!

Instructions

1.

There’s a children’s song we always get stuck in our head: If You’re Happy and You Know It. Let’s honor it by translating it into code!

Write a function, clapYourHands(). Your function should take in two boolean arguments. The first represents happiness and the second whether or not they “know it”.

If both are TRUE the function should return the string "CLAP!". Otherwise, it should return the string ":(".

You should use the && operator to accomplish this task.

2.

Test your function! You should invoke your function at least twice—once with inputs that return "CLAP!" and once with inputs that do NOT. Use echo so that the return value of each function call is printed to the terminal.

Folder Icon

Take this course for free

Already have an account?