if, else, elseif & Ternary ExpressionsConditional statements perform different actions based on whether specified conditions evaluate to true or false.
flowchart TD
A["Start Condition Check"] --> B{"If (Condition 1)"}
B -- True --> C["Execute Block 1"]
B -- False --> D{"ElseIf (Condition 2)"}
D -- True --> E["Execute Block 2"]
D -- False --> F["Execute Else Default Block"]
C & E & F --> G["Continue Script Execution"]
// Standard if...elseif...else
if ($score >= 90) {
$grade = 'A';
} elseif ($score >= 80) {
$grade = 'B';
} else {
$grade = 'C';
}
// Ternary Operator Shorthand
$status = ($age >= 18) ? "Adult" : "Minor";
// Short Ternary (Elvis Operator)
$displayName = $nickname ?: $fullName; // Uses $fullName if $nickname is falsy
<?php
declare(strict_types=1);
function evaluateCreditApplication(int $creditScore, float $annualIncome, bool $hasDefaults): string
{
// Guard clause checking immediate rejection criteria
if ($hasDefaults || $creditScore < 600) {
return "Rejected: Credit score or history fails risk threshold.";
}
if ($creditScore >= 750 && $annualIncome >= 60000.0) {
return "Approved: Tier-1 Preferred Customer Rate.";
} elseif ($creditScore >= 680 && $annualIncome >= 40000.0) {
return "Approved: Standard Rate.";
} else {
return "Manual Review Required: Co-signer required.";
}
}
// Ternary expression evaluation
$userRole = "admin";
$canDelete = ($userRole === "admin") ? true : false;
echo evaluateCreditApplication(780, 85000.0, false) . "
";
echo "Can Delete Records?: " . ($canDelete ? "Yes" : "No") . "
";
if blocks.($cond ? $a : $b) for simple assignments; do not nest ternaries within ternaries.(($a && $b) || $c).Write a function checkAccess(int $age, bool $isVIP) that returns "Granted" if $isVIP is true OR $age >= 21, and "Denied" otherwise!
Sign in to track your learning journey, earn industry-recognized certificates, and join our elite developer community.
Quick Access With
Experiment with the code from this lesson in our interactive playground.