Skip to Content
Learn
Logical Operators and Compound Conditions
Nested Conditional Statements

In the previous lesson, we explored the foundations of making decisions in programming: booleans and conditionals. In this lesson, we’ll deepen the complexity of our programs’ decision-making capabilities—we’ll be able to make programs where each decision made sends our program on a different route where it might encounter additional decisions.

We wrote some code to illustrate our decision-making process when taking an elevator. Read through the code to make sense of the process:

$is_elevator_here = true; $elevator_direction = "down"; $my_direction = "up"; $is_button_pushed = false; if ($is_elevator_here){ if ($elevator_direction === $my_direction){ echo "I'm in the elevator."; } else { if ($is_button_pushed){ echo "I'm waiting...!"; } else { echo "I'm pushing the button."; } } } else { if ($is_button_pushed){ echo "I'm waiting..."; } else { echo "I'm pushing the button."; } }

Notice that in order to implement this decision-making process with code, we nested conditionals inside each other. This is one way to make more complicated programs. In this lesson, we’ll also learn a new set of operators which will allow us to craft more elaborate decision-making programs. By the end, you’ll be equipped to make powerful, dynamic programs.

Instructions

1.

You’re going to use nested conditionals to create a function both(). Your function should have two boolean parameters. If the first parameter is TRUE and if the second parameter is TRUE, your function should return the string "both". Otherwise, it should return "not both".

There many ways to accomplish this (you’ll learn a great one later in this lesson), but for this task, you need to use nested conditionals.

2.

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

Folder Icon

Take this course for free

Already have an account?