PHP Conditions

← Back to Index


Example 1: If / Else Condition

Evaluating a student score of 78:

$score = 78;

if ($score >= 90)      { echo "Excellent! You earned an A."; }
elseif ($score >= 80)  { echo "Great job! You earned a B."; }
elseif ($score >= 70)  { echo "Good work! You earned a C."; }
elseif ($score >= 60)  { echo "You passed with a D. Keep studying!"; }
else                   { echo "Unfortunately, you did not pass."; }
    

Good work! You earned a C.


Example 2: Switch / Case Statement

Checking what type of day "Wednesday" is:

$day = "Wednesday";

switch ($day) {
    case "Monday":
        echo "Start of the work week!"; break;
    case "Tuesday":
    case "Wednesday":
    case "Thursday":
        echo "Midweek grind - you're doing great!"; break;
    case "Friday":
        echo "Almost the weekend. Finish strong!"; break;
    case "Saturday":
    case "Sunday":
        echo "It's the weekend! Time to relax."; break;
    default:
        echo "That is not a valid day name."; break;
}
    

Midweek grind - you're doing great!


Explanation

Conditional statements allow a PHP script to make decisions and execute different blocks of code depending on whether a condition is true or false. The if/else structure tests a Boolean expression — if true the first block runs, if false the else block runs. Multiple elseif branches can be chained to handle many possible outcomes. The switch/case statement is best used when comparing a single variable against many specific values. PHP checks each case in order until it finds a match then runs that block. A break statement ends each case to prevent fall-through into the next one. The default block runs when no case matches, acting like a final else. Conditions are fundamental to building dynamic PHP applications that respond intelligently to different data and user input.

INFOST 440 — Activity 3 — Nyla Broughton