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

while repeats while a condition is true. The condition must be a bool in Rust. PHP coerces the condition to boolean.

Rust

fn main() {
    let mut number = 3;
    while number != 0 {
        println!("{}!", number);
        number -= 1;
    }
    println!("Liftoff!");
}

PHP

<?php
$number = 3;
while ($number !== 0) {
    echo "$number!\n";
    $number--;
}
echo "Liftoff!\n";

Comparison

  • Rust: Condition must be bool; no truthy/falsy conversion.
  • PHP: Condition coerced to boolean (0, "", null, false are falsy).
  • Rust: No do-while; use loop with break at the end if needed.
  • PHP: do { } while ($cond) for at-least-one execution.

References

What's next

Next: The for keyword.

From PHP to Rust — Rust Syntax and Functions