Does php have foreach syntax?

藏色散人
Release: 2023-03-14 18:30:02
Original
1227 people have browsed it

php中是有foreach语法的,php foreach语法结构提供了遍历数组的简单方式,其语法如“foreach (iterable_expression as $value)statement”。

Does php have foreach syntax?

本文操作环境:Windows7系统、PHP7.1版、Dell G3电脑。

php有没有foreach语法

php有foreach语法。

foreach语法结构提供了遍历数组的简单方式。foreach 仅能够应用于数组和对象,如果尝试应用于其他数据类型的变量,或者未初始化的变量将发出错误信息。

有两种语法:

foreach (iterable_expression as $value) statement foreach (iterable_expression as $key => $value) statement
Copy after login

第一种格式遍历给定的 iterable_expression 迭代器。每次循环中,当前单元的值被赋给 $value。

第二种格式做同样的事,只除了当前单元的键名也会在每次循环中被赋给变量 $key。

注意 foreach 不会修改类似 current() 和 key() 函数所使用的数组内部指针。

还能够自定义遍历对象。

可以很容易地通过在 $value 之前加上 & 来修改数组的元素。此方法将以引用赋值而不是拷贝一个值。

Copy after login

注意:

数组最后一个元素的 $value 引用在 foreach 循环之后仍会保留。建议使用 unset() 来将其销毁。 否则你会遇到下面的情况:

 $value) { // $arr[3] 会被 $arr 的每一项值更新掉… echo "{$key} => {$value} "; print_r($arr); } // 直到最终倒数第二个值被复制到最后一个值 // output: // 0 => 2 Array ( [0] => 2, [1] => 4, [2] => 6, [3] => 2 ) // 1 => 4 Array ( [0] => 2, [1] => 4, [2] => 6, [3] => 4 ) // 2 => 6 Array ( [0] => 2, [1] => 4, [2] => 6, [3] => 6 ) // 3 => 6 Array ( [0] => 2, [1] => 4, [2] => 6, [3] => 6 ) ?>
Copy after login

可以通过引用来遍历数组常量的值:

Copy after login

注意:

foreach 不支持用 “@” 来抑制错误信息的能力。

示例:

 $v.\n"; $i++; } /* foreach 示例 3:key 和 value */ $a = array( "one" => 1, "two" => 2, "three" => 3, "seventeen" => 17 ); foreach ($a as $k => $v) { echo "\$a[$k] => $v.\n"; } /* foreach 示例 4:多维数组 */ $a = array(); $a[0][0] = "a"; $a[0][1] = "b"; $a[1][0] = "y"; $a[1][1] = "z"; foreach ($a as $v1) { foreach ($v1 as $v2) { echo "$v2\n"; } } /* foreach 示例 5:动态数组 */ foreach (array(1, 2, 3, 4, 5) as $v) { echo "$v\n"; } ?>
Copy after login

推荐学习:《PHP视频教程

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

Related labels:
source:php.cn
Statement of this Website
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
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!