PHP 8.5 While Loop Function

The while loop syntax in PHP 8.5 has not changed; it remains fully compatible with PHP 4, 5, 7, and 8.x. PHP 8.5 primarily introduces features such as the pipe operator (|>), URI extension, and array_first() / array_last() functions, which are unrelated to the while loop.

Basic Syntax

while (expr)
statement

It can also use curly braces to wrap multiple statements, or use the alternative syntax while (expr): ... endwhile;.

Key Point: The condition is checked at the beginning of each loop iteration. If the condition is false initially, the loop body will not execute even once.

Example 1: Basic Counting

<?php
$i = 1;
while ($i <= 10) {
echo $i++;
}
?>

Output: 12345678910. $i++ first outputs the value before incrementing, then increments.

Example 2: Searching in an Array

<?php
$customers = array("Huang", "Smith", "Jones");
$testvar = "no";
$k = 0;
while ($testvar != "yes") {
if ($customers[$k] == "Smith") {
$testvar = "yes";
echo "Smith<br />";
} else {
echo "$customers[$k], not Smith<br />";
}
$k++;
}
?>

This is a typical scenario for using while: the number of iterations is not predetermined and depends on a certain condition (finding a target value).

Relationship with PHP 8.5 New Features

PHP 8.5 does not modify the while loop syntax. The new features introduced in this version are primarily reflected in other areas, for example:

1.array_first() / array_last(): Simplify obtaining the first and last values of an array.
2.Pipe Operator |>: Optimizes the readability of chained function calls.
3.URI Extension: Replaces the non-standard parse_url() function.

These new features can be used in combination with while loops, but the while loop itself has no syntax changes.