以下为学习孔祥盛主编的《PHP编程基础与实例教程》(第二版)所做的笔记。
数组遍历语言结构
1. foreach ( array as $value )
程序:
1 <?php 2 $interests[2] = "music"; 3 $interests[5] = "movie"; 4 $interests[1] = "computer"; 5 $interests[] = "software"; 6 foreach ( $interests as $value) { 7 echo $value."<br/>"; 8 } 9 ?>
输出:
music
movie
computer
software
2. foreach( array as $key=>$value )
程序:
1 <?php 2 $interests[2] = "music"; 3 $interests[5] = "movie"; 4 $interests[1] = "computer"; 5 $interests[] = "software"; 6 foreach ( $interests as $key=>$value) { 7 echo $key."=>".$value."<br/>"; 8 } 9 ?>
输出:
2=>music 5=>movie 1=>computer 6=>software
foreach 语言结构除了可以实现对数组的遍历,还可以实现数组元素的键或值的修改。
以下程序1、程序2、程序3,只有程序1、2实现了数组元素值的修改。
程序1:
1 <?php 2 $interests[2] = "music"; 3 $interests[5] = "movie"; 4 $interests[1] = "computer"; 5 $interests[] = "software"; 6 foreach ( $interests as $key=>&$value) { //注意这里的 &$value 7 $value = "I like ".$value; 8 } 9 print_r($interests); 10 //Array ( [2] => I like music [5] => I like movie [1] => I like computer [6] => I like software ) 11 ?>
输出:
Array ( [2] => I like music [5] => I like movie [1] => I like computer [6] => I like software )
程序2:
1 <?php 2 $interests[2] = "music"; 3 $interests[5] = "movie"; 4 $interests[1] = "computer"; 5 $interests[] = "software"; 6 foreach ( $interests as $key=>$value) { 7 $interests[$key] = "I like ".$value; 8 } 9 print_r($interests); 10 ?>
输出:
Array ( [2] => I like music [5] => I like movie [1] => I like computer [6] => I like software )
程序3:
1 <?php 2 $interests[2] = "music"; 3 $interests[5] = "movie"; 4 $interests[1] = "computer"; 5 $interests[] = "software"; 6 foreach ( $interests as $key=>$value) { 7 $value = "I like ".$value; 8 } 9 print_r($interests); 10 ?>
输出:
Array ( [2] => music [5] => movie [1] => computer [6] => software )
foreach 语言结构操作的是数组的一个拷贝,而不是数组本身。在foreach 遍历数组的过程,尽量不要使用数组指针函数操作 “当前指针”(current),否则会事与愿违。
程序:
1 <?php 2 $interests[2] = "music"; 3 $interests[5] = "movie"; 4 $interests[1] = "computer"; 5 $interests[] = "software"; 6 foreach ( $interests as $key=>$value) { 7 echo "I like ".current($interests)."!<br/>"; 8 echo $value."<br/>"; 9 } 10 print_r($interests); 11 ?>
输出:
I like music! music I like music! movie I like music! computer I like music! software Array ( [2] => music [5] => movie [1] => computer [6] => software )