Learn
Logical Operators and Compound Conditions
The || Operator

Expressions that use logical operators evaluate to boolean values.

The logical operator || takes two different boolean values or expressions as its operands and returns a single boolean value. It returns TRUE if either its left operand or its right operand evaluate to TRUE. We can use || in situations where more than one condition should lead to the same outcome.

TRUE || TRUE; // Evaluates to: TRUE FALSE || TRUE; // Evaluates to: TRUE TRUE || FALSE; // Evaluates to: TRUE FALSE || FALSE; // Evaluates to: FALSE

Let’s think about an example we might encounter in web development: when requesting a password change for a web application, the password can only be changed by either the user themselves or an administrator.

$is_admin = FALSE; $is_user = TRUE; if ($is_admin || $is_user){ echo "You can change the password"; }

In the code above, the condition $is_admin || $is_user evaluates to TRUE and "You can change the password" is printed to the terminal. Note that while $is_admin is FALSE, $is_user is TRUE. The || operator is inclusive—it evaluates to TRUE if either or both of the operands are TRUE.

Instructions

1.

We have a special quirk: we’ll eat only when we’re hungry or if it’s dessert. Somehow we always have room for dessert… Let’s use the logical || operator to represent this situation with code.

Write a function willWeEat(). Your function should take as its first argument a string representing a meal type, and as its second argument a boolean of whether or not we’re hungry.

If either the meal is "dessert" or it’s TRUE that we’re hungry, the function should return "Yum. Thanks!". Otherwise, it should return "No thanks. We're not hungry."

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

2.

We tested your function, but you should test it yourself! Invoke your function at least twice—once with inputs that return "Yum. Thanks!"and once with inputs that return "No thanks. We're not hungry.". Be sure to use echo to print the return values to the terminal.

Folder Icon

Take this course for free

Already have an account?