• 博客园logo
  • 会员
  • 众包
  • 新闻
  • 博问
  • 闪存
  • 赞助商
  • HarmonyOS
  • Chat2DB
    • 搜索
      所有博客
    • 搜索
      当前博客
  • 写随笔 我的博客 短消息 简洁模式
    用户头像
    我的博客 我的园子 账号设置 会员中心 简洁模式 ... 退出登录
    注册 登录
小许学习笔记
博客园    首页    新随笔    联系   管理    订阅  订阅
5_PHP数组_3_数组处理函数及其应用_5_数组遍历语言结构

以下为学习孔祥盛主编的《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 )

 

posted on 2019-11-10 08:54  xiaoxustudy  阅读(243)  评论(0)    收藏  举报
刷新页面返回顶部
博客园  ©  2004-2025
浙公网安备 33010602011771号 浙ICP备2021040463号-3