$v){statement block;}"."/> $v){statement block;}".">

Home  >  Article  >  Backend Development  >  Can php foreach traverse arrays?

Can php foreach traverse arrays?

青灯夜游
青灯夜游Original
2022-05-25 19:54:192037browse

php foreach can traverse arrays. foreach is a statement specially designed for traversing an array. This statement traverses the array regardless of the array subscript. Can be used to traverse index arrays with discontinuous subscripts and associative arrays with strings as subscripts; the syntax is "foreach($arr as $k => $v){statement block;}".

Can php foreach traverse arrays?

The operating environment of this tutorial: windows7 system, PHP7.1 version, DELL G3 computer

php foreach statement can traverse the array.

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 for 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.

Two syntaxes for foreach to traverse arrays

Grammar format 1:

foreach ($array as $value){
    语句块;
}

Traverse to A certain $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 assign the value of the current array to $value, the key name is 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 of foreach traversing array

Example 1:

<?php
header("Content-type:text/html;charset=utf-8");
$arr=array(1=>"1","a"=>"red",2=>"2","b"=>"green","c"=>"blue");
var_dump($arr);
foreach ($arr as $value) { 
    echo $value . "<br/>";
} 
?>

Can php foreach traverse arrays?

Example 2 :

<?php
header("Content-type:text/html;charset=utf-8");
$arr=array(1=>"1","a"=>"red",2=>"2","b"=>"green","c"=>"blue");
var_dump($arr);
foreach ($arr as $key => $value) { 
    echo "键名为:".$key.",键值为:".$value . "<br/>";
} 
?>

Can php foreach traverse arrays?

Recommended learning: "PHP Video Tutorial", "PHP ARRAY"

The above is the detailed content of Can php foreach traverse arrays?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn