Originally published on php2rust.dev — part of the PHP to Rust course. View this lesson on the original site.

Conditional execution with if, else if, and else. Rust requires the condition to be a bool; PHP coerces values to boolean.

Rust

fn main() {
    let number = 7;
    if number < 5 {
        println!("Less than 5");
    } else if number > 5 {
        println!("Greater than 5");
    } else {
        println!("Exactly 5");
    }

    // if is an expression
    let result = if number > 0 { "positive" } else { "non-positive" };
    println!("Result: {}", result);
}

PHP

<?php
$number = 7;
if ($number < 5) {
    echo "Less than 5\n";
} elseif ($number > 5) {
    echo "Greater than 5\n";
} else {
    echo "Exactly 5\n";
}

$result = $number > 0 ? "positive" : "non-positive";

Comparison

  • Rust: Condition must be bool; no implicit conversion from numbers or pointers.
  • PHP: Conditions can be any type; truthy/falsy conversion applies.
  • Rust: if can be used as an expression; branches must have compatible types.
  • PHP: Use ternary ? : for conditional expressions.

References

What's next

Next: Loop constructs.

From PHP to Rust — Rust Syntax and Functions