Detailed explanation and example code of using PHP foreach loop

PHP is a widely used server-side scripting language that provides rich looping structures for processing data in arrays and collections. Among them, the foreach loop is a particularly useful loop structure, which can traverse each element of an array or iterable object and perform a specific operation on each element. This article will introduce the use of PHP foreach loop in detail and provide some example code to help understand.

Grammar form:

foreach ($array as $value) {
    // 执行操作
}

In the above syntax, $arrayit is the array or iterable object to be traversed and $valuethe value of the element currently traversed. Within the loop body, we can use $valuevariables to access the value of the current element and perform corresponding operations.

In addition to the above basic form, the foreach loop can also use the key name and key value form to traverse the array. The specific syntax is as follows:

foreach ($array as $key => $value) {
    // 执行操作
}

In this form, $keyit represents the key name of the currently traversed element and $valuerepresents the value of the current element. This form of loop is suitable for situations where you need to access key names and key values ​​at the same time.

Below we use some examples to demonstrate the use of foreach loop.

Example 1: Traverse an array

$fruits = array(

Guess you like

Origin blog.csdn.net/RcuEmacs_Lisp/article/details/133399187