当前位置:首页>php>第6篇:PHP数组与常用函数

第6篇:PHP数组与常用函数

  • 2026-09-02 19:37:03
第6篇:PHP数组与常用函数

PHP数组与常用函数

数组是PHP中最强大的数据结构之一。可以把数组想象成一排编好号的储物柜,每个柜子都有一个编号(索引),里面可以存放各种数据。PHP的数组既可以当普通数组用,也可以当字典/映射表用,功能非常强大。

一、创建数组

<?php// 方式1:使用 array()$fruits1 = array("苹果", "香蕉", "橙子");// 方式2:使用 [](PHP 5.4+ 推荐)$fruits2 = ["苹果", "香蕉", "橙子"];// 方式3:先声明再添加$colors = [];$colors[] = "红色";    // 自动索引0$colors[] = "绿色";    // 自动索引1$colors[] = "蓝色";    // 自动索引2echo"水果:" . implode(", ", $fruits2) . "\n";echo"颜色:" . implode(", ", $colors) . "\n";?>

代码讲解:

  • array()是传统写法,[]是现代写法,效果相同
  • $array[] = $value会往数组末尾添加新元素
  • implode(", ", $array)把数组用逗号连接成字符串

二、索引数组

索引从0开始的数组:

<?php// 学生的成绩列表$scores = [85, 92, 78, 96, 67, 88, 73, 95, 82];echo"成绩列表:" . implode(", ", $scores) . "\n";echo"第1个成绩:{$scores[0]}\n";     // 第一个元素,索引是0echo"第3个成绩:{$scores[2]}\n";     // 第三个元素,索引是2echo"共有" . count($scores) . "个成绩\n";  // count() 计算元素个数// 遍历数组echo"\n逐个显示:\n";for ($i = 0; $i < count($scores); $i++) {echo"第" . ($i + 1) . "个成绩:" . $scores[$i] . "\n";}// 计算总分和平均分$total = array_sum($scores);  // 求和$average = $total / count($scores);  // 平均值echo"\n总分:{$total}\n";echo"平均分:" . round($average, 1) . "\n";  // round() 四舍五入到1位小数?>

代码讲解:

  • 索引从0开始,不是从1开始!这是新手最容易犯的错误
  • count()返回数组元素个数
  • array_sum()返回数组所有元素的和

三、关联数组

用字符串作为键的数组,类似于其他语言中的Map或字典:

<?php// 定义一个学生信息$student = ["name" => "王小明","age" => 20,"gender" => "男","major" => "计算机科学与技术","grade" => "大三","gpa" => 3.85// 平均绩点];// 访问元素echo"学生姓名:" . $student["name"] . "\n";echo"学生专业:" . $student["major"] . "\n";// 修改和添加元素$student["age"] = 21;        // 修改现有键$student["phone"] = "13800138000";  // 添加新键值对// 遍历关联数组echo"\n学生完整信息:\n";foreach ($studentas$key => $value) {echo"{$key}:{$value}\n";}// 获取所有键或所有值echo"\n所有键:" . implode(", ", array_keys($student)) . "\n";echo"所有值:" . implode(", ", array_values($student)) . "\n";?>

代码讲解:

  • "键名" => $值的语法创建键值对
  • 访问时用$array["键名"]
  • 遍历关联数组用foreach ($array as $key => $value)
  • array_keys()返回所有键组成的数组
  • array_values()返回所有值组成的数组

四、二维数组

数组里面再放数组,形成表格结构:

<?php// 班级成绩表:每个学生一行$class_scores = [    ["name" => "张三", "math" => 85, "english" => 92, "chinese" => 88],    ["name" => "李四", "math" => 78, "english" => 85, "chinese" => 90],    ["name" => "王五", "math" => 96, "english" => 88, "chinese" => 92],    ["name" => "赵六", "math" => 67, "english" => 73, "chinese" => 70],];// 打印成绩表echo"班级成绩表:\n";echostr_repeat("-", 40) . "\n";  // str_repeat 重复字符串printf("%-8s %6s %8s %8s\n", "姓名", "数学", "英语", "语文");  // 格式化输出echostr_repeat("-", 40) . "\n";foreach ($class_scoresas$student) {printf("%-8s %6d %8d %8d\n", $student["name"], $student["math"], $student["english"], $student["chinese"]    );}// 计算每个人的平均分echo"\n个人平均分:\n";foreach ($class_scoresas$student) {$avg = ($student["math"] + $student["english"] + $student["chinese"]) / 3;echosprintf("%s:%.1f分\n", $student["name"], $avg);}?>

代码讲解:

  • $class_scores[0]是一个包含学生信息的数组
  • $class_scores[0]["name"]是"张三"
  • printf()是格式化输出函数,%-8s表示左对齐的8字符字符串
  • sprintf()和printf类似,但返回字符串而不是直接输出

五、常用数组函数

数组指针函数

<?php$colors = ["红", "绿", "蓝", "黄"];echo"当前: " . current($colors) . "\n";   // 当前元素:红echo"下一个: " . next($colors) . "\n";    // 指针下移:绿echo"当前: " . current($colors) . "\n";   // 当前元素:绿echo"上一个: " . prev($colors) . "\n";    // 指针上移:红echo"末尾: " . end($colors) . "\n";       // 最后一个:黄echo"开头: " . reset($colors) . "\n";    // 重置到开头:红?>

数组搜索和检查

<?php$fruits = ["苹果", "香蕉", "橙子", "葡萄", "西瓜"];// 检查键是否存在if (isset($fruits[2])) {echo"第三个水果存在:" . $fruits[2] . "\n";}// 检查值是否存在if (in_array("香蕉", $fruits)) {echo"香蕉在数组中\n";}// 获取值的键$key = array_search("橙子", $fruits);echo"橙子的键是:{$key}\n";// in_array 的高级用法:严格比较类型$numbers = [1, 2, 3, 4, 5];if (in_array("3", $numbers, true)) {  // true 开启严格模式echo"找到3(严格比较)\n";} else {echo"没找到3(严格比较)\n";  // 因为"3"是字符串,3是整数}?>

数组排序

<?php// 数值数组排序$scores = [85, 92, 78, 96, 67, 88];sort($scores);  // 从小到大排序echo"从小到大:" . implode(", ", $scores) . "\n";rsort($scores);  // 从大到小排序echo"从大到小:" . implode(", ", $scores) . "\n";// 关联数组排序:按值排序$student = ["张三" => 85, "李四" => 92, "王五" => 78];asort($student);  // 保持键值关联,按值排序print_r($student);  // 打印数组(调试用)// 按键排序ksort($student);print_r($student);?>

代码讲解:

  • sort()会改变原数组,且不保留键名
  • asort()按值排序,保留键名
  • ksort()按键排序,保留键名
  • print_r()是调试利器,能清晰展示数组结构

数组过滤和映射

<?php$numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];// array_filter:过滤数组$evens = array_filter($numbers, fn($n) => $n % 2 == 0);echo"偶数:" . implode(", ", $evens) . "\n";$odds = array_filter($numbers, fn($n) => $n % 2 != 0);echo"奇数:" . implode(", ", $odds) . "\n";// array_map:对每个元素执行操作$squared = array_map(fn($n) => $n * $n, $numbers);echo"平方:" . implode(", ", $squared) . "\n";// 组合使用:找出偶数并求平方和$even_squares = array_map(    fn($n) => $n * $n,array_filter($numbers, fn($n) => $n % 2 == 0));echo"偶数的平方:" . implode(", ", $even_squares) . "\n";?>

数组合并和切片

<?php$array1 = ["a", "b", "c"];$array2 = ["d", "e", "f"];// 合并数组$merged = array_merge($array1, $array2);echo"合并后:" . implode(", ", $merged) . "\n";// 关联数组合并(相同键会覆盖)$info1 = ["name" => "张三", "age" => 20];$info2 = ["name" => "李四", "city" => "北京"];$merged_info = array_merge($info1, $info2);print_r($merged_info);// array_slice:截取数组的一部分$numbers = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9];echo"\n前5个:" . implode(", ", array_slice($numbers, 0, 5)) . "\n";echo"中间3个:" . implode(", ", array_slice($numbers, 3, 3)) . "\n";echo"最后3个:" . implode(", ", array_slice($numbers, -3)) . "\n";?>

六、实战:学生成绩管理系统

<?php// 学生数据$students = [    ["name" => "王小明", "math" => 85, "english" => 92, "chinese" => 88],    ["name" => "李梅",   "math" => 92, "english" => 88, "chinese" => 95],    ["name" => "张强",   "math" => 78, "english" => 85, "chinese" => 72],    ["name" => "刘芳",   "math" => 88, "english" => 76, "chinese" => 90],    ["name" => "陈伟",   "math" => 95, "english" => 91, "chinese" ="];// 1. 计算每个学生的总分和平均分echo "=== 学生成绩统计 ===\n\n";$results = [];foreach ($students as $student) {$total = $student["math"] + $student["english"] + $student["chinese"];$avg = $total / 3;$results[] = [        "name" => $student["name"],        "total" => $total,        "avg" => round($avg, 1)    ];}// 按总分降序排序usort($results, fn($a, $b) => $b["total"] - $a["total"]);echo "排名  姓名    总分  平均分\n";echo str_repeat("-", 25) . "\n";foreach ($results as $index => $r) {    printf("%2d. %-8s %4d  %5.1f\n", $index + 1, $r["name"], $r["total"], $r["avg"]);}// 2. 找出单科最高分echo "\n=== 单科最高分 ===\n";$math_scores = array_column($students, "math");$english_scores = array_column($students, "english");$chinese_scores = array_column($students, "chinese");$math_top = array_keys($math_scores, max($math_scores))[0];$english_top = array_keys($english_scores, max($english_scores))[0];$chinese_top = array_keys($chinese_scores, max($chinese_scores))[0];echo "数学最高分:{$students[$math_top]["name"]},{$students[$math_top]["math"]}分\n";echo "英语最高分:{$students[$english_top]["name"]},{$students[$english_top]["english"]}分\n";echo "语文最高分:{$students[$chinese_top]["name"]},{$students[$chinese_top]["chinese"]}分\n";?>

代码讲解:

  • array_column($array, "key")提取数组中某个键的所有值
  • usort()使用自定义函数排序
  • array_keys()配合max()找出最大值对应的键

七、写在最后

数组是PHP编程中最常用的数据结构。熟练掌握各种数组函数,能大大提高开发效率。多阅读PHP官方文档,记住那些最常用的函数组合。

最新文章

随机文章