Originally published on php2rust.dev — part of the PHP to Rust course. View this lesson on the original site.
loop creates an infinite loop. Use break to exit and continue to skip to the next iteration. PHP has no direct equivalent; use while (true).
Rust
fn main() {
let mut counter = 0;
loop {
counter += 1;
println!("Counter: {}", counter);
if counter == 5 {
break;
}
}
println!("Done");
// break can return a value
let result = loop {
counter += 1;
if counter >= 10 {
break counter * 2;
}
};
println!("Result from break: {}", result);
}
PHP
<?php
$counter = 0;
while (true) {
$counter++;
echo "Counter: $counter\n";
if ($counter === 5) {
break;
}
}
echo "Done\n";
Comparison
- Rust:
loopis a dedicated construct;breakcan return a value. - PHP:
while (true)is the usual pattern;breakdoes not return. - Rust:
continueskips to the next iteration. - PHP: Same behaviour for
continue.
References
What's next
Next: The while keyword.
From PHP to Rust — Rust Syntax and Functions