Skip to content
Classroom

Conditional Macros

Built-in functions for testing conditions and making logical comparisons.

Comparison Operators

Equality

if ($a == $b) {  // Loose equality (type coercion)
    // Both values are equal
}

if ($a === $b) {  // Strict equality (exact type and value)
    // Both values and types are identical
}

Inequality

if ($a != $b) {  // Not equal
    // Values are different
}

if ($a !== $b) {  // Not strictly equal
    // Values or types are different
}

Numeric Comparisons

$lt = ($a < $b)    // less than
$gt = ($a > $b)    // greater than
$le = ($a <= $b)   // less than or equal
$ge = ($a >= $b)   // greater than or equal

Logical Operators

There is no feedback or hint variable

Control code only sets $variables. A bare word such as feedback is read as a quoted string, so feedback = "…" becomes 'feedback' = "…" — a PHP syntax error that stops the whole block from running. Store the message in a variable ($fb below) and place $fb in the question text, or use a feedback macro. The student's entry is $stuanswers[$thisq] and is empty until they submit; $answer is your correct answer, not theirs.

&& (AND)

Both conditions must be true.

if ($age >= 18 && $registered == true) {
    $fb = "You are eligible.";
}

|| (OR)

At least one condition must be true.

if ($month == "December" || $month == "January") {
    $fb = "It's winter (in Northern Hemisphere).";
}

! (NOT)

Negate a condition.

if (!$isComplete) {
    $fb = "Your assignment is not complete.";
}

if ($n != 42) {
    $fb = "That's not the answer.";
}

If/Else Statements

Simple If

if ($pct >= 90) {
    $fb = "Excellent work!";
}

If/Else

if ($a > $b) {
    $bigger = $a;
} else {
    $bigger = $b;
}

If/Elseif/Else

if ($pct >= 90) {
    $fb = "A: Excellent";
} elseif ($pct >= 80) {
    $fb = "B: Good";
} elseif ($pct >= 70) {
    $fb = "C: Satisfactory";
} else {
    $fb = "Below 70: Needs improvement";
}

String Comparisons

Case-Sensitive

$stu = $stuanswers[$thisq]
if ($stu == "Paris") {
    $fb = "Correct capital!";
}

Case-Insensitive

$stu = $stuanswers[$thisq]
if (strtolower($stu) == strtolower("paris")) {
    $fb = "Correct (case-insensitive)!";
}
$stu = $stuanswers[$thisq]
if ($stu !== null && stringpos("Darwin", $stu) >= 0) {
    $fb = "You mentioned Darwin correctly.";
}

Array Operations with Conditionals

Check if Value in Array

$correct_answers = ["Paris", "London", "Berlin"];
$stu = $stuanswers[$thisq]

if (in_array($stu, $correct_answers)) {
    $fb = "That's a correct European capital!";
}

Count Array Elements

$responses = ["A", "C"];

if (count($responses) == 2) {
    $fb = "You selected 2 options.";
}

Ternary Operator

Shorthand for if/else:

$message = ($age >= 18) ? "Adult" : "Minor";

$result = ($correct) ? "Excellent!" : "Try again";

Examples

Feedback Based on Magnitude of Error

$correctAnswer = 25
$stu = $stuanswers[$thisq]
$fb = ""

if (!is_numeric($stu)) {
    $fb = "";
} elseif (comparenumbers($correctAnswer, $stu)) {
    $fb = "Perfect!";
} elseif (abs($stu - $correctAnswer) <= 2) {
    $fb = "Very close! Check your rounding.";
} elseif (abs($stu - $correctAnswer) <= 5) {
    $fb = "In the right ballpark. Review your calculation.";
} else {
    $fb = "Not quite. Start over and check each step.";
}

Conditional Hints

You do not need if for hints that change with each attempt. Put them in the $hints array: the engine shows $hints[$attemptn], where $attemptn is the attempt number (0 before the first submission), and keeps showing the last hint once the student runs past the end. Hints appear only when the assessment's hint setting is on. They appear only where you put $hintloc in the question text. Assign $hints after $answer if a hint quotes it.

$hints[0] = "Try using the distance formula."
$hints[1] = "Distance = √((x₂-x₁)² + (y₂-y₁)²)"
$hints[2] = "The answer is $answer"

Validating Student Response

$stu = $stuanswers[$thisq]
$fb = ""
if ($stu === null) {
    $fb = "";
} elseif (stringlen($stu) < 5) {
    $fb = "Your answer is too short.";
} elseif (stringlen($stu) > 100) {
    $fb = "Your answer is too long.";
} elseif (stringpos("yes", strtolower($stu)) >= 0) {
    $fb = "Good, you acknowledged the question.";
}

Conditional Question Display

There is no @if / @endif template syntax in question text. Choose the content in control code and place the variable in the question text.

Common Control — setup:

$level = rand(1, 3)
if ($level == 1) {
    $eqn = "x + 5 = 12";
    $answer = 7;
} elseif ($level == 2) {
    $eqn = "2x - 3 = 15";
    $answer = 9;
} else {
    $eqn = "3x + 4 = -11";
    $answer = -5;
}

Question Text:

Solve: `$eqn`

Checking Multiple Conditions

if ($age >= 18 && $pts >= 80 && !$alreadyPassed) {
    $fb = "You qualify for the advanced program!";
} elseif ($age < 18) {
    $fb = "You must be 18 or older.";
} elseif ($pts < 80) {
    $fb = "You need a score of at least 80.";
} elseif ($alreadyPassed) {
    $fb = "You've already completed this level.";
}

Comparison Macros

Use these, not ==, to compare a student's entry with a value: they apply a tolerance and accept equivalent forms. The compare… macros return true or false, except that comparentuples (on a mismatch) and comparenumberswithunits (when the values differ) return nothing, which also tests as false. A tolerance is relative unless written with a leading bar, e.g. "|0.01" for an absolute tolerance of 0.01.

Macro Compares Defaults
comparenumbers($a, $b, $tol) two numbers; either may be an expression string such as "sqrt(2)" $tol = .001, relative to $a
comparefunctions($a, $b, $vars, $tol, $domain) two expressions, or two equations, at 20 sample points $vars = "x", $tol = .001, $domain = "-10,10"
comparesameform($a, $b, $vars) same form, not just the same value; terms and factors may be reordered ("2+2x" matches "2x+2", "2(x+1)" does not) $vars = "x"
comparenumberswithunits($a, $b, $tol) quantities with units, e.g. "5 m" and "500 cm" $tol = .001
comparentuples($a, $b, $tol) n-tuples such as "(1,2)" $tol = .001
comparelogic($a, $b, $vars) logical expressions —
comparesetexp($a, $b, $vars) set expressions —
scorestring($answer, $showanswer, $words, $stuanswers, $thisq) accepts the student's text if it contains every word in $words; returns array($answer, $showanswer) —
ifthen($cond, $iftrue, $iffalse) returns $iftrue or $iffalse —
$c1 = comparenumbers(1.001, 1)                  // true: within 0.1%
$c2 = comparenumbers(3.14, pi, "|0.01")         // true: within 0.01
$f1 = comparefunctions("2(x+1)", "2x+2")        // true: same values
$s1 = comparesameform("2(x+1)", "2x+2")         // false: different form
$u1 = comparenumberswithunits("5 m", "500 cm")  // true
$t = ifthen($a > 0, "positive", "not positive")

Operator Precedence

Order of evaluation (highest to lowest): 1. ! (NOT) 2. *, /, % (Multiplication, division, modulo) 3. +, - (Addition, subtraction) 4. <, >, <=, >= (Comparisons) 5. ==, !=, ===, !== (Equality) 6. && (AND) 7. || (OR)

Use parentheses to override:

if (($a || $b) && $c) {  // Parentheses matter
    $ok = true;
}

Common Mistakes

  • Using = instead of ==: if ($a = 5) assigns; use if ($a == 5) for comparison
  • Forgetting else cases: Always consider what happens if the condition is false
  • String comparison mistakes: numeric strings compare as numbers ("10" > "2" is true), but other strings compare character by character and case-sensitively ("Paris" == "paris" is false)
  • Loose vs strict equality: 0 == false is true; 0 === false is false

See Also