foreach structure

WBOY
WBOYOriginal
2016-08-08 09:20:241396browse

This article mainly introduces foreach in PHP, in addition to the ordinary foreach(array_expression_r_r as $value){} format, another way of writing foreach, foreach(array_expression_r_r as $key => $value){}.

As we all know, use the simple foreach(array_expression_r_r as $value){} format, such as:

<?php
$arr=array("one","two","three");
foreach($arr as $a){ 
	echo $a;
}
?>

The result of the operation is to output the elements in the arr array one by one.

foreach executes the reset(array) function by itself, points the internal pointer of the array to the first element, and returns the value of this element. Afterwards, the execution is continuously moved backward and the arr array is output.

However, if I want to operate on the subscripts of each element while using foreach to traverse arr, I have to use the foreach(array_expression_r_r as $key => $value){} structure.

For example, the following program:

<?php
$arr=array("one","two","three");
foreach($arr as $key=>$value){ 
	echo "arr[$key]=$value<br>"; 
} 
?>

The running result is as follows:


Using $key, you can get the subscript of each element during the loop, which is this element position in this array.

Copyright Statement: This article is an original article by the blogger and may not be reproduced without the blogger's permission.

The above has introduced the foreach structure, including aspects of it. I hope it will be helpful to friends who are interested in PHP tutorials.

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