search
Homephp教程php手册php之foreach遍历数组

php之foreach遍历数组

foreach

(PHP 4, PHP 5)

The foreach construct provides an easy way to iterate over arrays. foreach works only on arrays and objects, and will issue an error when you try to use it on a variable with a different data type or an uninitialized variable. There are two syntaxes:

foreach (array_expression as $value)
    statement
foreach (array_expression as $key => $value)
    statement

The first form loops over the array given by array_expression. On each iteration, the value of the current element is assigned to $value and the internal array pointer is advanced by one (so on the next iteration, you'll be looking at the next element).

The second form will additionally assign the current element's key to the $key variable on each iteration.

It is possible to customize object iteration.

Note:

When foreach first starts executing, the internal array pointer is automatically reset to the first element of the array. This means that you do not need to call reset() before a foreach loop.

As foreach relies on the internal array pointer, changing it within the loop may lead to unexpected behavior.

In order to be able to directly modify array elements within the loop precede $value with &. In that case the value will be assigned by reference.

<?php <br> $arr = array(1, 2, 3, 4);<br> foreach ($arr as &$value) {<br> $value = $value * 2;<br> }<br> // $arr is now array(2, 4, 6, 8)<br> unset($value); // break the reference with the last element<br> ?>

Referencing $value is only possible if the iterated array can be referenced (i.e. if it is a variable). The following code won't work:

<?php <br> foreach (array(1, 2, 3, 4) as &$value) {<br> $value = $value * 2;<br> }<br> ?> Warning

Reference of a $value and the last array element remain even after the foreach loop. It is recommended to destroy it by unset().

Note:

foreach does not support the ability to suppress error messages using '@'.

You may have noticed that the following are functionally identical:

<?php <br> $arr = array("one", "two", "three");<br> reset($arr);<br> while (list(, $value) = each($arr)) {<br> echo "Value: $value<br>\n";<br> }<br> <br> foreach ($arr as $value) {<br> echo "Value: $value<br>\n";<br> }<br> ?>

The following are also functionally identical:

<?php <br> $arr = array("one", "two", "three");<br> reset($arr);<br> while (list($key, $value) = each($arr)) {<br> echo "Key: $key; Value: $value<br>\n";<br> }<br> <br> foreach ($arr as $key => $value) {<br> echo "Key: $key; Value: $value<br>\n";<br> }<br> ?>

Some more examples to demonstrate usage:

<?php <br> /* foreach example 1: value only */<br> <br> $a = array(1, 2, 3, 17);<br> <br> foreach ($a as $v) {<br> echo "Current value of \$a: $v.\n";<br> }<br> <br> /* foreach example 2: value (with its manual access notation printed for illustration) */<br> <br> $a = array(1, 2, 3, 17);<br> <br> $i = 0; /* for illustrative purposes only */<br> <br> foreach ($a as $v) {<br> echo "\$a[$i] => $v.\n";<br> $i++;<br> }<br> <br> /* foreach example 3: key and value */<br> <br> $a = array(<br> "one" => 1,<br> "two" => 2,<br> "three" => 3,<br> "seventeen" => 17<br> );<br> <br> foreach ($a as $k => $v) {<br> echo "\$a[$k] => $v.\n";<br> }<br> <br> /* foreach example 4: multi-dimensional arrays */<br> $a = array();<br> $a[0][0] = "a";<br> $a[0][1] = "b";<br> $a[1][0] = "y";<br> $a[1][1] = "z";<br> <br> foreach ($a as $v1) {<br> foreach ($v1 as $v2) {<br> echo "$v2\n";<br> }<br> }<br> <br> /* foreach example 5: dynamic arrays */<br> <br> foreach (array(1, 2, 3, 4, 5) as $v) {<br> echo "$v\n";<br> }<br> ?>

Unpacking nested arrays with list()

(PHP 5 >= 5.5.0)

PHP 5.5 added the ability to iterate over an array of arrays and unpack the nested array into loop variables by providing a list() as the value.

For example:

<?php <br> $array = [<br> [1, 2],<br> [3, 4],<br> ];<br> <br> foreach ($array as list($a, $b)) {<br> // $a contains the first element of the nested array,<br> // and $b contains the second element.<br> echo "A: $a; B: $b\n";<br> }<br> ?>

The above example will output:

A: 1; B: 2
A: 3; B: 4

You can provide fewer elements in the list() than there are in the nested array, in which case the leftover array values will be ignored:

<?php <br> $array = [<br> [1, 2],<br> [3, 4],<br> ];<br> <br> foreach ($array as list($a)) {<br> // Note that there is no $b here.<br> echo "$a\n";<br> }<br> ?>

The above example will output:

1
3

A notice will be generated if there aren't enough array elements to fill the list():

<?php <br> $array = [<br> [1, 2],<br> [3, 4],<br> ];<br> <br> foreach ($array as list($a, $b, $c)) {<br> echo "A: $a; B: $b; C: $c\n";<br> }<br> ?>

The above example will output:

Notice: Undefined offset: 2 in example.php on line 7
A: 1; B: 2; C: 

Notice: Undefined offset: 2 in example.php on line 7
A: 3; B: 4; C: 
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
php 怎么求2个数组相同的元素php 怎么求2个数组相同的元素Dec 23, 2022 am 10:04 AM

php求2个数组相同元素的方法:1、创建一个php示例文件;2、定义两个有相同元素的数组;3、使用“array_intersect($array1,$array2)”或“array_intersect_assoc()”方法获取两个数组相同元素即可。

c语言数组如何初始化c语言数组如何初始化Jan 04, 2023 pm 03:36 PM

C语言数组初始化的三种方式:1、在定义时直接赋值,语法“数据类型 arrayName[index] = {值};”;2、利用for循环初始化,语法“for (int i=0;i<3;i++) {arr[i] = i;}”;3、使用memset()函数初始化,语法“memset(arr, 0, sizeof(int) * 3)”。

用Python实现动态数组:从入门到精通用Python实现动态数组:从入门到精通Apr 21, 2023 pm 12:04 PM

Part1聊聊Python序列类型的本质在本博客中,我们来聊聊探讨Python的各种“序列”类,内置的三大常用数据结构——列表类(list)、元组类(tuple)和字符串类(str)的本质。不知道你发现没有,这些类都有一个很明显的共性,都可以用来保存多个数据元素,最主要的功能是:每个类都支持下标(索引)访问该序列的元素,比如使用语法Seq[i]​。其实上面每个类都是使用数组这种简单的数据结构表示。但是熟悉Python的读者可能知道这3种数据结构又有一些不同:比如元组和字符串是不能修改的,列表可以

c++数组怎么初始化c++数组怎么初始化Oct 15, 2021 pm 02:09 PM

c++初始化数组的方法:1、先定义数组再给数组赋值,语法“数据类型 数组名[length];数组名[下标]=值;”;2、定义数组时初始化数组,语法“数据类型 数组名[length]=[值列表]”。

javascript怎么给数组中增加元素javascript怎么给数组中增加元素Nov 04, 2021 pm 12:07 PM

增加元素的方法:1、使用unshift()函数在数组开头插入元素;2、使用push()函数在数组末尾插入元素;3、使用concat()函数在数组末尾插入元素;4、使用splice()函数根据数组下标,在任意位置添加元素。

php怎么判断数组里面是否存在某元素php怎么判断数组里面是否存在某元素Dec 26, 2022 am 09:33 AM

php判断数组里面是否存在某元素的方法:1、通过“in_array”函数在数组中搜索给定的值;2、使用“array_key_exists()”函数判断某个数组中是否存在指定的key;3、使用“array_search()”在数组中查找一个键值。

php 怎么去除第一个数组元素php 怎么去除第一个数组元素Dec 23, 2022 am 10:38 AM

php去除第一个数组元素的方法:1、新建一个php文件,并创建一个数组;2、使用“array_shift”方法删除数组首个元素;3、通过“print_”r输出数组即可。

详解Go语言中删除数组元素的方法详解Go语言中删除数组元素的方法Mar 22, 2023 pm 03:21 PM

在Go语言中,数组是一种重要的数据类型。它与其他语言的数组一样,是一组相同类型的数据组成,可以通过一个索引来访问数组中的元素。在某些情况下,我们需要从一个数组中删除元素,本文将会介绍在Go语言中如何实现数组删除。

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment