Four methods: 1. Use "for($i=0;$i

The operating environment of this tutorial: windows7 system, PHP7.1 version, DELL G3 computer
Method 1: Use for statement traversal
The for loop will pre-define the variable that controls the number of loops in the for statement, so the for loop statement can perform loop operations according to the known number of loops, which is suitable for situations where the number of loops is clearly known. The number of times the script needs to be run.
The syntax format of the for loop is as follows:
for (初始化语句; 循环条件; 变量更新--自增或自减) {
语句块;
} Statement analysis:
Initialization statement (expression 1): mainly to initialize a The variable value is used to set a counter, which is the value at the beginning of the loop; this statement is only executed during the first loop and will not be executed again in the future.
Loop condition (expression 2): Restriction condition for loop execution, used to control whether to execute the code in the loop body; if the condition is TRUE, the loop continues, if the condition is FALSE , the loop ends and exits the loop immediately.
Variable update (expression 3): an expression with an increment or decrement operation. Every time the loop is executed, the value of the counter is immediately modified so that the loop The conditions gradually become "untenable".
Statement block: Several codes that need to be executed when the condition is judged to be true.
Example
<?php
header("Content-type:text/html;charset=utf-8");
$array= array(2,"数学","梨子",3.14,"榴莲",12);
for ($i=0; $i < count($array); $i++) {
echo $array[$i] . "<br/>";
}
?>Output result:
2 数学 梨子 3.14 榴莲 12
Method 2: Use foreach statement to traverse
foreach is a statement specially designed for traversing arrays. It is a commonly used method when traversing arrays. It provides great convenience in traversing arrays. After PHP5, you can also traverse objects (foreach can only be applied to arrays and objects).
The foreach statement traverses the array regardless of the array subscript, and can be used for discontinuous index arrays and associative arrays with strings as subscripts.
foreach statement analysis
Let’s first understand the foreach statement, which has two grammatical formats:
Grammar format 1:
foreach ($array as $value){
语句块;
}Traverse the given $array array and assign the value of the current array to $value in each loop.
Syntax format 2:
foreach ($array as $key => $value){
语句块;
}Traverse the given $array array, and in each loop, the value of the current array will be assigned to $value, and the key name will be assigned to $key.
Explanation:
When the foreach statement loops, the pointer inside the array will move forward one step, so that the next array element will be obtained in the next loop. Stop traversing and exit the loop until it reaches the end of the array.
Example:
<?php
header("Content-type:text/html;charset=utf-8");
$array= array("香蕉","苹果","梨子","橙子","橘子","榴莲");
foreach ($array as $val){
echo "值是:" . $val ;
echo "<br/>";
}
echo "<br/>";
foreach ($array as $key => $value) {
echo "键名为:".$key.",键值为:".$value . "<br/>";
}
?>Output result:

Method 3 : Use the while statement each() list() to traverse
each() function returns the current key value in the array and moves the array pointer forward. After each() is executed, the array pointer will stay at the next element in the array or at the last element when the end of the array is reached.
The list() function is used to assign values to a set of variables in one operation.
while loop each() function list() function can traverse the array, let’s take a look at the code example below:
<?php
header("Content-type:text/html;charset=utf-8");
$array= array("香蕉","苹果","梨子","橙子","橘子","榴莲");
while( list($key, $val) = each($array) ) {
echo "$key => $val<br>";
}
?>Output result:
Method 4: Use do-while statement next() key() current() to traverse
Every array in PHP has one Internal pointer, that is, array pointer; this pointer will point to an element in the array (this element is the current element of the array, and by default initially points to the first element in the array).
next() function can return the value of the next element pointed to by the internal pointer of the array, and returns FALSE when there are no more elements.
key() function is used to obtain the key name of the current element in the array.
current() function returns the key value of the current element of the array.
Use do-while loop next() key() current() to traverse the array and obtain the key name and key value of the array element.
Let’s take a look at the code example below:
<?php
header("Content-type:text/html;charset=utf-8");
$array= array("香蕉","苹果","梨子","橙子","橘子","榴莲");
do{
echo key($array)." => ".current($array)."<br>";
}while(next($array));
?>Output result:

After the traversal is completed, the array pointer will point to the last one For array elements, we can use the reset() function to reset the array pointer and redirect the internal pointer in the array to the first element.
Recommended: "PHP Video Tutorial"
The above is the detailed content of What are the four ways to traverse an array in php. For more information, please follow other related articles on the PHP Chinese website!
ACID vs BASE Database: Differences and when to use each.Mar 26, 2025 pm 04:19 PMThe article compares ACID and BASE database models, detailing their characteristics and appropriate use cases. ACID prioritizes data integrity and consistency, suitable for financial and e-commerce applications, while BASE focuses on availability and
PHP Secure File Uploads: Preventing file-related vulnerabilities.Mar 26, 2025 pm 04:18 PMThe article discusses securing PHP file uploads to prevent vulnerabilities like code injection. It focuses on file type validation, secure storage, and error handling to enhance application security.
PHP Input Validation: Best practices.Mar 26, 2025 pm 04:17 PMArticle discusses best practices for PHP input validation to enhance security, focusing on techniques like using built-in functions, whitelist approach, and server-side validation.
PHP API Rate Limiting: Implementation strategies.Mar 26, 2025 pm 04:16 PMThe article discusses strategies for implementing API rate limiting in PHP, including algorithms like Token Bucket and Leaky Bucket, and using libraries like symfony/rate-limiter. It also covers monitoring, dynamically adjusting rate limits, and hand
PHP Password Hashing: password_hash and password_verify.Mar 26, 2025 pm 04:15 PMThe article discusses the benefits of using password_hash and password_verify in PHP for securing passwords. The main argument is that these functions enhance password protection through automatic salt generation, strong hashing algorithms, and secur
OWASP Top 10 PHP: Describe and mitigate common vulnerabilities.Mar 26, 2025 pm 04:13 PMThe article discusses OWASP Top 10 vulnerabilities in PHP and mitigation strategies. Key issues include injection, broken authentication, and XSS, with recommended tools for monitoring and securing PHP applications.
PHP XSS Prevention: How to protect against XSS.Mar 26, 2025 pm 04:12 PMThe article discusses strategies to prevent XSS attacks in PHP, focusing on input sanitization, output encoding, and using security-enhancing libraries and frameworks.
PHP Interface vs Abstract Class: When to use each.Mar 26, 2025 pm 04:11 PMThe article discusses the use of interfaces and abstract classes in PHP, focusing on when to use each. Interfaces define a contract without implementation, suitable for unrelated classes and multiple inheritance. Abstract classes provide common funct


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

Zend Studio 13.0.1
Powerful PHP integrated development environment

DVWA
Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

EditPlus Chinese cracked version
Small size, syntax highlighting, does not support code prompt function

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

Safe Exam Browser
Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.






