PHP foreach()用法和实例
原网址:
http://blog.csdn.net/china_skag/article/details/6444727
PHP 4 引入了 foreach 结构,和 Perl 以及其他语言很像。这只是一种遍历数组简便方法。foreach 仅能用于数组,当试图将其用于其它数据类型或者一个未初始化的变量时会产生错误。有两种语法,第二种比较次要但却是第一种的有用的扩展。
foreach (array_expression as $value)
statement
foreach (array_expression as $key => $value)
statement
第一种格式遍历给定的 array_expression 数组。每次循环中,当前单元的值被赋给 $value 并且数组内部的指针向前移一步(因此下一次循环中将会得到下一个单元)。
第二种格式做同样的事,只是除了当前单元的键名也会在每次循环中被赋给变量 $key。
先来看第一个语句,这个语句比较简单,array_expression指的是一个数组表达式,as $val语句将顺序取得该数组的值并保存到$val变量中,此种方法只能取得数组内的值,而不能取得数组的下标索引值。例如:
$myArray=array("1"=>"val1","2"=>"val2","3"=>"val3");
foreach($myArray as $val) {
print($val." ");
}
其结果会输出:val1 val2 val3
再来看看第二种格式,第二种格式除了能像第一种格式一样得到数组内元素的值外,还能得到元素的索引值,并保存到$key变量中,如果数组的索引值未经过人工设定,则返回系统默认的设定值,
看正面例子:
先看一个简单的一维数组:
$myArray=array("1"=>"val1","2"="val2","3"=>"val3");
foreach($myArray as $key=>$val) {
print($key."=>".$val.";");
}
该程序将出输出:1=>val1;2=>val2;3=>val3;,接下来我们再来看一个复杂一点的二维数组遍历,程序如下:
$myArray=array(
"1"=>array("11"=>"val11","12"=>"val12","13"=>"val13"),
"2"=>array("21"=>"val21","22"=>"val22","23"=>"val23"),
"3"=>array("31"=>"val31","32"=>"val32","33"=>"val33")
);
print("
- ");
- ".$key." ");
- ".$key."=>".$val." ");
foreach($myArray as $key=>$val) {
print("
if (is_array($val)) { //判断$val的值是否是一个数组,如果是,则进入下层遍历
print("
- ");
foreach($val as $key=>$val) {
print("
}
print("
}
}
print("
输出结果:
1
11=>val11
12=>val12
13=>val13
2
21=>val21
22=>val22
23=>val23
3
31=>val31
32=>val32
33=>val33
- 和
- 是 标签,作用是显示个实心小圆点和空心小圆点。
由于上面的是一个二维数组,在第一次遍历后所得到的$val值将是一个数组,所以我在遍历中加了一个判断,以便进行二层数组遍历。
再通过一个实例解惑
$a = array("1"=>"语文","2"=>"数学","3"=>"英语");
$b = array("1"=>"95","2"=>"99","3"=>"92");
foreach($a as $key=>$value){
echo $value;
echo $b[$key]."
";
}
?>
问题是为什么输出数组$b中的值要用$b[$key]而不是$b[$value]?
这是为什么呢?
$a = array("1"=>"语文","2"=>"数学","3"=>"英语");
上面这个和下面这个是完全一样的
$a[1]="语文";
$a[2]="数学"
$a[3]=“英语”
我们输出上面的数组是怎么输出的呢?
肯定是echo $a[1];
对不对?
如果没有疑问我们继续!!!!
------------------------------
简单说foreach
它的格式是这样的foreach(数组名 as 下标=>值)
下标也就是上面的$a[1],这里的1就是数组的下标!
到这你应该明白了,为什么是$a[$key]这样输出
你记住不管怎么变,数组的输出方法永远是$a[1],不会是$a['语文']
================================================================
foreach()有两种用法:
1: foreach(array_name as $value){
statement;
}
这里的array_name是你要遍历的数组名,每次循环中,array_name数组的当前元素的值被赋给$value,并且数组内部的下标向下移一步,也就是下次循环回得到下一个元素。
2:foreach(array_name as $key => $value){
statement;
}
这里跟第一种方法的区别就是多了个$key,也就是除了把当前元素的值赋给$value外,当前元素的键值也会在每次循环中被赋给变量$key。键值可以是下标值,也可以是字符串。比如book[0]=1中的“0”,book[id]="001"中的“id”.

What’s still popular is the ease of use, flexibility and a strong ecosystem. 1) Ease of use and simple syntax make it the first choice for beginners. 2) Closely integrated with web development, excellent interaction with HTTP requests and database. 3) The huge ecosystem provides a wealth of tools and libraries. 4) Active community and open source nature adapts them to new needs and technology trends.

PHP and Python are both high-level programming languages that are widely used in web development, data processing and automation tasks. 1.PHP is often used to build dynamic websites and content management systems, while Python is often used to build web frameworks and data science. 2.PHP uses echo to output content, Python uses print. 3. Both support object-oriented programming, but the syntax and keywords are different. 4. PHP supports weak type conversion, while Python is more stringent. 5. PHP performance optimization includes using OPcache and asynchronous programming, while Python uses cProfile and asynchronous programming.

PHP is mainly procedural programming, but also supports object-oriented programming (OOP); Python supports a variety of paradigms, including OOP, functional and procedural programming. PHP is suitable for web development, and Python is suitable for a variety of applications such as data analysis and machine learning.

PHP originated in 1994 and was developed by RasmusLerdorf. It was originally used to track website visitors and gradually evolved into a server-side scripting language and was widely used in web development. Python was developed by Guidovan Rossum in the late 1980s and was first released in 1991. It emphasizes code readability and simplicity, and is suitable for scientific computing, data analysis and other fields.

PHP is suitable for web development and rapid prototyping, and Python is suitable for data science and machine learning. 1.PHP is used for dynamic web development, with simple syntax and suitable for rapid development. 2. Python has concise syntax, is suitable for multiple fields, and has a strong library ecosystem.

PHP remains important in the modernization process because it supports a large number of websites and applications and adapts to development needs through frameworks. 1.PHP7 improves performance and introduces new features. 2. Modern frameworks such as Laravel, Symfony and CodeIgniter simplify development and improve code quality. 3. Performance optimization and best practices further improve application efficiency.

PHPhassignificantlyimpactedwebdevelopmentandextendsbeyondit.1)ItpowersmajorplatformslikeWordPressandexcelsindatabaseinteractions.2)PHP'sadaptabilityallowsittoscaleforlargeapplicationsusingframeworkslikeLaravel.3)Beyondweb,PHPisusedincommand-linescrip

PHP type prompts to improve code quality and readability. 1) Scalar type tips: Since PHP7.0, basic data types are allowed to be specified in function parameters, such as int, float, etc. 2) Return type prompt: Ensure the consistency of the function return value type. 3) Union type prompt: Since PHP8.0, multiple types are allowed to be specified in function parameters or return values. 4) Nullable type prompt: Allows to include null values and handle functions that may return null values.


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

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Atom editor mac version download
The most popular open source editor

SublimeText3 Linux new version
SublimeText3 Linux latest version

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

SublimeText3 English version
Recommended: Win version, supports code prompts!

SAP NetWeaver Server Adapter for Eclipse
Integrate Eclipse with SAP NetWeaver application server.