CodeBlanks Logo Icon CodeBlanks

Summary - Conditionals

PHP course · Beginner · Lesson 41/116

Build a day-of-the-week app using if, switch and the ternary operator.

Summary - Conditionals

In this group you learned three conditional tools: if/elseif/else for ordered checks, switch for branching on one variable's values, and ? : (ternary) for one-line assignments.

A day-of-the-week app combines them: use switch to turn a number into a day name, if or the ternary to check for weekend, and default for unexpected values. Picking the right tool for each job keeps code readable.

Exercise Day name app

The $day variable is already declared. Write a switch: for case 1 print 'Monday', for case 2 print 'Tuesday', for case 3 print 'Wednesday', for default print 'Unknown'. Put a break; at the end of each case.

Show example solution
... break; structure.
Example solution:
<?php
$day = 3;
// Day name
switch ($day) {
  case 1:
    echo 'Monday';
    break;
  case 2:
    echo 'Tuesday';
    break;
  case 3:
    echo 'Wednesday';
    break;
  default:
    echo 'Unknown';
}

Exercise Weekend check

The $day variable is already declared (1-7 range). With the ternary operator, assign to $type: when $day >= 6 use 'weekend', otherwise 'weekday'. Then print with echo $type;.

Show example solution
'weekday';
Example solution:
<?php
$day = 6;
// Weekend check
$type = $day >= 6 ? 'weekend' : 'weekday';
echo $type;

Test yourself

  1. Which tool fits a one-line conditional assignment?

    • switch
    • while
    • for
    • ternary
    Show answer

    ternary — Correct. The ternary (? :) makes a conditional assignment in one line.

  2. Write the switch keyword

    $day = 3;
    ____ ($day) {
      case 3:
        echo 'Wednesday';
        break;
    }
    Show answer
    $day = 3;
    switch ($day) {
      case 3:
        echo 'Wednesday';
        break;
    }

All lessons in Beginner