5_PHP数组_3_数组处理函数及其应用_5_数组遍历语言结构
2024-09-04 04:29:24
以下为学习孔祥盛主编的《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 )
最新文章
- css常用样式
- 【kate整理】matlab求商,求余数
- bookstores网上书店测试缺陷报告1
- 省市县三级联动(webFrom...DropdownList)
- angular学习的一些小笔记(中)之基础ng指令
- [游戏模版1] MFC最小框架(base function including)
- x264命令参数与代码中变量的对应关系
- WPF中Application.Current的使用
- 阿里云ECS被攻击
- PHP Array函数分类
- Shell语法中的test命令用法
- hdu 1543 Paint the Wall
- Go学习笔记 - 使用jsonrpc进行远程访问
- rsync 密钥文件错误问题总结
- Android EditText常用属性
- python的Web框架,类视图
- VUE组件 之 倒计时(防刷新)
- 《算法》第二章部分程序 part 2
- js获取图片的原始尺寸
- linux系统方面的知识