


Summary of 3 methods of PHP looping through arrays list(), each() and while
This article mainly introduces the summary of the three methods list(), each() and while of PHP looping through arrays. The focus of this article is on the mixed use of these three methods. Friends who need it can refer to it
①each() function
each() function needs to pass an array as a parameter, return the key/value pair of the current element in the array, and move the array pointer backward to the next The position of an element. Key/value pairs are returned as a mixed associative and indexed array with 4 elements, with keys 0, 1, key, and value. The key name 0 is the same as the value corresponding to key, which is the key name of the array element, while 1 and value contain the value of the array element. If the internal pointer goes beyond the end of the array, each() returns FALSE. The use of each() function is as follows:
Copy code The code is as follows:
<?php $contact = array("ID" => 1,"姓名" => "高某","公司" => "A公司","地址" => "北京市",); $id = each($contact); //返回数组$contact中第一个元素的键/值对,是带有4个元素的数组 print_r($id); //输出数组$id:Array([1]=>1,[value]=>1,[0]=>ID,[key]=>ID) $name = each($contact); //返回数组$contact中的第二个元素的键/值对,是带有4个元素的数组 print_r($name); //输出Array([1]=>高某,[value]=>高某,[0]=>姓名,[key]=>姓名) $company = each($contact); print_r($company); //输出Array([1]=>A公司,[value]=>A公司,[0]=>公司,[key]=>公司) $address = each($contact); print_r($address); //输出Array([1]=>北京市,[value]=>北京市,[0]=>地址,[key]=>地址) $no = each($contact); var_dump($no); //输出bool(false) ?>
②list() function
This is not a real function, but a language construct of PHP. list() assigns values to a set of variables in one step, that is, assigns the values in the array to some variables. list() can only be used with numerically indexed arrays and assumes that array indices start at 0. The syntax format is as follows:
Copy code The code is as follows:
list(mixed varname,mixed…) = array_expression
The use of the list() statement is very different from other functions, and Instead of directly receiving an array as a parameter. Instead, the value of each element in the array is assigned to each parameter in the list() function through assignment using the "=" operator. The list() function in turn converts each parameter in it into a variable that can be used directly in the script. The usage is as follows:
Copy code The code is as follows:
<?php $info = array('coffee','brown','caffeine'); list($drink,$color,$power) = $info; list($drink,,$power) = $info; //变量的值是数组中第一个和第三个值 list( , ,$power) = $info; //变量值是数组中第三个元素的值 ?>
After understanding the usage of the list() function through the above example, combine the each() function with the list () function is used in combination. The code is as follows:
Copy code The code is as follows:
<?php $contact = array("ID" => 1,"姓名" => "高某","公司" => "A公司","地址" => "北京市",); list($key,$value) = each($contact); echo "$key => $value"; //输出变量$key和$value,中间使用“=>”分割 ?>
③while loop traverses the array
each( introduced earlier ) and list() statements, it is not difficult to understand how to use a while loop to traverse an array. The syntax format used is as follows:
Copy code The code is as follows:
while(list($key,$value) = each(array_expression)){ 循环体 }
This union format traverses the given array_expression array. In each loop of the while() statement, the each() statement assigns the key of the current array element to the first parameter variable $key of the list() function. And assign the value in the current array element to the second parameter variable $value in the list() function, and after the each() statement is executed, the pointer inside the array will be moved back one step, so next time while() When the statement loops, the key/value pair of the next element in the array will be obtained. Until the end of the array, the each() statement returns FALSE, and the while() statement stops the loop and ends the traversal of the array.
Copy code The code is as follows:
<?php $contact = array( "ID" => 1, "姓名" => "高某", "公司" => "A公司", "地址" => "北京市", "电话" => "(010)98765432", "EMAIL" => "gao@brophp.com", ); //以HTML列表的方式输出数组中每个元素的信息 echo '<dl>一个联系人信息:'; while(list($key,$value) = each($contact)){ echo "<dd>$key : $value</dd>"; } echo '</dl>'; ?>
You can also nest and traverse multi-dimensional arrays in the same way. Although the results of while traversing the array are the same as those of the freach statement, there are differences between the two methods. After using the while statement to traverse the array, the each() statement has pointed the internal pointer of the passed array parameter to the end of the array. When the while statement is used again to traverse the same array, the array pointer is already at the end of the array, and the each() statement directly returns FALSE, and the while statement will not be executed in the loop. Only call the reset() function before the while statement is executed to reset the array pointer to the first element. The foreach statement will automatically reset the pointer position of the array. When foreach starts to execute, the pointer inside the array will automatically point to the first unit. This means there is no need to call the reset() function before the foreach loop.
Related recommendations:
Detailed explanation of PHP page encoding declaration method (header or meta)
in php Rounding function code (floor function, ceil function, round and intval)
The above is the detailed content of Summary of 3 methods of PHP looping through arrays list(), each() and while. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics



PHP 8.4 brings several new features, security improvements, and performance improvements with healthy amounts of feature deprecations and removals. This guide explains how to install PHP 8.4 or upgrade to PHP 8.4 on Ubuntu, Debian, or their derivati

Visual Studio Code, also known as VS Code, is a free source code editor — or integrated development environment (IDE) — available for all major operating systems. With a large collection of extensions for many programming languages, VS Code can be c

This tutorial demonstrates how to efficiently process XML documents using PHP. XML (eXtensible Markup Language) is a versatile text-based markup language designed for both human readability and machine parsing. It's commonly used for data storage an

JWT is an open standard based on JSON, used to securely transmit information between parties, mainly for identity authentication and information exchange. 1. JWT consists of three parts: Header, Payload and Signature. 2. The working principle of JWT includes three steps: generating JWT, verifying JWT and parsing Payload. 3. When using JWT for authentication in PHP, JWT can be generated and verified, and user role and permission information can be included in advanced usage. 4. Common errors include signature verification failure, token expiration, and payload oversized. Debugging skills include using debugging tools and logging. 5. Performance optimization and best practices include using appropriate signature algorithms, setting validity periods reasonably,

A string is a sequence of characters, including letters, numbers, and symbols. This tutorial will learn how to calculate the number of vowels in a given string in PHP using different methods. The vowels in English are a, e, i, o, u, and they can be uppercase or lowercase. What is a vowel? Vowels are alphabetic characters that represent a specific pronunciation. There are five vowels in English, including uppercase and lowercase: a, e, i, o, u Example 1 Input: String = "Tutorialspoint" Output: 6 explain The vowels in the string "Tutorialspoint" are u, o, i, a, o, i. There are 6 yuan in total

If you are an experienced PHP developer, you might have the feeling that you’ve been there and done that already.You have developed a significant number of applications, debugged millions of lines of code, and tweaked a bunch of scripts to achieve op

Static binding (static::) implements late static binding (LSB) in PHP, allowing calling classes to be referenced in static contexts rather than defining classes. 1) The parsing process is performed at runtime, 2) Look up the call class in the inheritance relationship, 3) It may bring performance overhead.

What are the magic methods of PHP? PHP's magic methods include: 1.\_\_construct, used to initialize objects; 2.\_\_destruct, used to clean up resources; 3.\_\_call, handle non-existent method calls; 4.\_\_get, implement dynamic attribute access; 5.\_\_set, implement dynamic attribute settings. These methods are automatically called in certain situations, improving code flexibility and efficiency.
