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