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

Rust provides loop (infinite), while, and for. PHP has while, do-while, for, and foreach.

Rust

fn main() {
    // loop: infinite until break
    let mut count = 0;
    loop {
        count += 1;
        if count == 2 {
            break;
        }
    }

    // while: conditional
    while count < 4 {
        count += 1;
    }

    // for: iterate over iterator
    for x in 1..=3 {
        println!("{}", x);
    }
}

PHP

<?php
// while
while ($condition) { }

// do-while
do { } while ($condition);

// for
for ($i = 0; $i < 5; $i++) { }

// foreach
foreach ($arr as $x) { }

Comparison

  • Rust: loop for “repeat until break”; no C-style for; for works on iterators.
  • PHP: C-style for for index loops; foreach for arrays/iterables.
  • Rust: break and continue work in all loop types; break can return a value.
  • PHP: break and continue with optional level.

References

What's next

Next: The loop keyword.

From PHP to Rust — Rust Syntax and Functions