PHP基础-数组

【写在前面】资源分享【7天有效期】

php 复制代码
夸克网盘「PHP项目实战教程」
链接:https://pan.quark.cn/s/078b0196ee91

数组(Array) 是一种可以在一个变量中存储多个值的数据结构。PHP 的数组非常灵活,支持数值索引、字符串键,以及多维数组结构。

PHP 中数组的三种类型
类型 描述
索引数组 使用数字作为键名(从 0 开始)
关联数组 使用字符串作为键名(类似字典)
多维数组 数组中的元素也是数组,用于构建更复杂的数据结构
索引数组
定义方式
php 复制代码
// 方法 1:
$colors=array("red", "green", "blue");

// 方法 2(PHP 5.4+):
$colors= ["red", "green", "blue"];
访问元素
php 复制代码
<?php
$colors=array("red", "green", "blue");
var_dump($colors[0]);
$animals= ["cat", "dog", "bird"];
var_dump($animals[0]);
?>
遍历元素
php 复制代码
<?php
$colors=array("red", "green", "blue");
foreach($colorsas$color){
echo$color . "<br>";
}

echo"------------------------------------------<br>";
$animals= ["cat", "dog", "bird"];
foreach($animalsas$animal){
echo$animal . "<br>";
}
?>
关联数组
定义方式
php 复制代码
$person= [
    "name"=>"小明",
    "age"=>25,
    "gender"=>"male"
];
访问元素
php 复制代码
echo$person["name"]; // 输出:小明
echo$person["age"];
echo$person["gender"];
遍历数组
php 复制代码
<?php
$person= [
    "name"=>"小明",
    "age"=>25,
    "gender"=>"male"
];

echocount($person) . "<br>"; //计算数组长度

//遍历数组
foreach($personas$key=>$value){
echo$key . ":" .  $value . "</br>";
}

?>
多维数组

多维数组中每个元素都是一个数组:

php 复制代码
$students= [
    ["小红", 18, "女"],
    ["小刚", 20, "男"],
    ["小美", 19, "女"]
];

echo$students[1][0]; // 输出:小刚
遍历数组
php 复制代码
<?php
$students= [
    ["小红", 18, "女"],
    ["小刚", 20, "男"],
    ["小美", 19, "女"]
];

foreach($studentsas$student){
    foreach($studentas$info){
echo$info . "";
    }
echo"<br>";    
}
?>
遍历多维关联数组
php 复制代码
<?php
$people= [
    "xiaoming"=> ["name"=>"小明", "age"=>18, "gender"=>"男"],
    "xiaohong"=> ["name"=>"小红", "age"=>19, "gender"=>"女"]
];

foreach ($peopleas$key=>$person) {
    echo"ID: $key<br>";
    foreach ($personas$attribute=>$value) {
        echo"$attribute: $value<br>";
    }
    echo"<hr>";
}

?>