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:
loopfor “repeat until break”; no C-stylefor;forworks on iterators. - PHP: C-style
forfor index loops;foreachfor arrays/iterables. - Rust:
breakandcontinuework in all loop types;breakcan return a value. - PHP:
breakandcontinuewith optional level.
References
What's next
Next: The loop keyword.
From PHP to Rust — Rust Syntax and Functions