ZetCode

PHP 数组

最后修改于 2025 年 2 月 16 日

在本文中,我们将展示如何在 PHP 中使用数组。

PHP 数组定义

数组是数据的集合。一个变量一次只能保存一个项目。数组可以保存多个项目。

注意:PHP 数组是一个集合,既可以用作列表,也可以用作映射。

PHP 提供了大量函数来修改、排序、合并、切片、打乱数组中的数据。有专门的数据库处理函数,用于从数据库查询中填充数组。还有一些其他函数返回数组。

PHP 数组初始化

数组可以使用一对 [] 括号或使用 array 函数进行初始化。

init1.php
<?php

$names = ["Jane", "Lucy", "Timea", "Beky", "Lenka"];

print_r($names);

我们创建一个 $names 数组,它存储五个女性的名字。print_r 函数打印有关变量的易于理解的信息。

$ php init1.php
Array
(
    [0] => Jane
    [1] => Lucy
    [2] => Timea
    [3] => Beky
    [4] => Lenka
)

从输出中,我们可以看到名字以及它们的索引,我们可以通过这些索引来访问它们。

传统上,数组是使用 array 函数初始化的。在最简单的形式中,该函数接受任意数量的用逗号分隔的值。

init2.php
<?php

$names = array("Jane", "Lucy", "Timea", "Beky", "Lenka");

print_r($names);

使用 array 函数创建了与前面相同的女性名字的数组。

可以通过将值分配给数组索引来初始化数组。

init3.php
<?php

$continents[0] = "America";
$continents[1] = "Africa";
$continents[2] = "Europe";
$continents[3] = "Asia";
$continents[4] = "Antarctica";
$continents[5] = "Australia";

print_r($continents);

我们通过将值分配给数组索引来创建 $continents 数组。“America” 的索引为 0,“Europe” 的索引为 2 等等。

init4.php
<?php

$continents = [ 1 => "America", 2 => "Africa",
    3 => "Europe", 4 => "Asia", 5 => "Antarctica",
    6 => "Australia" ];

print_r($continents);

在这个例子中,我们创建了带有指定索引的 $continents 数组。默认情况下,第一个索引是零。在我们的例子中,我们从 1 开始。

$ php init4.php
Array
(
    [1] => America
    [2] => Africa
    [3] => Europe
    [4] => Asia
    [5] => Antarctica
    [6] => Australia
)

现在我们有了一个包含我们选择的索引的大洲数组。

索引不必是连续的数字。

init5.php
<?php

$languages[10] = "PHP";
$languages[20] = "Python";
$languages[30] = "Ruby";
$languages[40] = "PERL";
$languages[50] = "Java";

print_r($languages);

在这个例子中,我们选择了数字 10、20、30、40 和 50 作为 $languages 数组的索引。

当我们对 PHP 数组进行赋值初始化时,我们可以省略索引。PHP 会自动为我们创建索引。

init6.php
<?php

$actors[] = "Philip Seymour Hoffman";
$actors[] = "Tom Cruise";
$actors[] = "Bill Paxton";
$actors[] = "Adrien Brody";
$actors[] = "Daniel Craig";

print_r($actors);

创建了一个演员数组。没有设置特定的索引。

$ php init6.php
Array
(
    [0] => Philip Seymour Hoffman
    [1] => Tom Cruise
    [2] => Bill Paxton
    [3] => Adrien Brody
    [4] => Daniel Craig
)

PHP 解释器创建了从零开始的连续索引。

init7.php
<?php

$novels[10] = "Doctor Zhivago";
$novels[11] = "War and Peace";
$novels[] = "In Cold Blood";
$novels[20] = "Crime and Punishment";
$novels[] = "Catch XII";

print_r($novels);

在这个脚本中,我们省略了两个索引。PHP 将添加它们。它将创建索引 12 和索引 21。

$ php init5.php
Array
(
    [10] => Doctor Zhivago
    [11] => War and Peace
    [12] => In Cold Blood
    [20] => Crime and Punishment
    [21] => Catch XII
)

PHP 已经自动创建了索引 12 和 21。

数组的键也可以是字符串。

init8.php
<?php

$countries = [
    "de" => "Germany", "sk" => "Slovakia",
    "us" => "United States", "ru" => "Russia",
    "hu" => "Hungaria", "pl" => "Poland" ];

echo $countries["de"] . "\n";
echo $countries["sk"] . "\n";

我们用字符串索引创建了一个 $countries 数组。

$ php init8.php
Germany
Slovakia

PHP 数组元素类型

一个 PHP 数组可以包含各种类型的元素。

types.php
<?php 

$vals = ['sky', true, -4, [1, 2, 3, 4]];

foreach ($vals as $val) {
    
    $t = gettype($val);

    $res = match($t) {

        'string' => 'value is a string',
        'integer' => 'value is an integer',
        'boolean' => 'value is a boolean', 
        'array' => 'value is an array',
        default => 'unknown type'
    };

    echo "$res\n";

}

在这个例子中,我们有一个包含不同类型元素的数组。使用 match 表达式和 gettype 函数,我们得到每个元素的类型。

$ php types.php 
value is a string
value is a boolean
value is an integer
value is an array

PHP 遍历数组

接下来,我们读取数组的内容。有几种方法可以显示数组中的数据。

peruse1.php
<?php

$languages[10] = "PHP";
$languages[20] = "Python";
$languages[30] = "Ruby";
$languages[40] = "PERL";
$languages[50] = "Java";

echo $languages[10], "\n";
echo $languages[20], "\n";
echo $languages[30], "\n";
echo $languages[40], "\n";
echo $languages[50], "\n";

我们可以通过它们的索引从数组中访问数据。

$ php peruse1.php
PHP
Python
Ruby
PERL
Java

我们已经将所有五种语言打印到控制台。

peruse2.php
<?php

$continents = [ "America", "Africa", "Europe",
    "Asia", "Australia", "Antarctica" ];

$len = count($continents);

for ($i = 0; $i < $len; $i++) {
    echo $continents[$i], "\n";
}

在这个例子中,我们使用 for 语句来遍历一个 $continents 数组。

$len = count($continents);

首先,我们使用 count 函数计算数组中的元素数量。

for ($i = 0; $i < $len; $i++) {
    echo $continents[$i], "\n";
}

for 循环通过索引 0..$len-1 打印数组中的元素。

peruse3.php
<?php

$continents = [ "America", "Africa", "Europe", "Asia",
    "Australia", "Antarctica" ];

foreach ($continents as $continent) {
    echo $continent, "\n";
}

遍历数组最简单的方法是使用 foreach 语句。该语句逐个遍历数组,并将当前元素放入临时 $continent 变量中。它在不使用其索引或键的情况下访问数据。

walk.php
<?php

$countries = [ "de" => "Germany", "sk" => "Slovakia",
    "us" => "United States", "ru" => "Russia",
    "hu" => "Hungaria", "pl" => "Poland" ];

function show_values($value, $key) {

    echo "The $key stands for the $value\n";
}

array_walk($countries, 'show_values');

在最后一个例子中,我们使用 array_walk 函数来遍历数组。它将一个用户函数应用于数组的每个成员。用户函数将项目的键和值作为参数。

$ php walk.php
The de stands for the Germany
The sk stands for the Slovakia
The us stands for the United States
The ru stands for the Russia
The hu stands for the Hungary
The pl stands for the Poland

我们在句子中将键和值都打印到控制台。

PHP 数组排序

首先,我们将对数组进行排序。

sort.php
<?php

$names = [ "Jane", "Rebecca", "Lucy", "Lenka", "Ada" ];

echo "Unsorted: \n";

foreach ($names as $name) {
    echo "$name ";
}

echo "\n";

sort($names);

echo "Sorted: \n";

foreach ($names as $name) {
    echo "$name ";
}

echo "\n";

在上面的脚本中,我们有一个 $names 数组。我们使用 sort 函数对数组的内容进行排序。

$ php sort.php
Unsorted:
Jane Rebecca Lucy Lenka Ada
Sorted:
Ada Jane Lenka Lucy Rebecca

脚本的输出显示了未排序和已排序的女性名字。

rsort 函数按降序对数组进行排序。

sort2.php
<?php

$numbers = [ 12, 3, 5, 1, 6, 7, 10, 0, 9, 8, 11];

sort($numbers);

echo "Ascending order: \n";

foreach ($numbers as $n) {
    echo "$n ";
}

echo "\n";

rsort($numbers);

echo "Descending order: \n";

foreach ($numbers as $n) {
    echo "$n ";
}

echo "\n";

这里有一个整数数组。它按升序和降序排序。

sort($numbers);

sort 函数按升序对整数进行排序。

rsort($numbers);

rsort 函数按降序对整数进行排序。

$ php sort2.php
Ascending order:
0 1 3 5 6 7 8 9 10 11 12
Descending order:
12 11 10 9 8 7 6 5 3 1 0

在下面的例子中,我们将展示如何对带重音的字符进行排序。

locale_sort.php
<?php

setlocale(LC_ALL, 'sk_SK.utf8');

$words = [ "ďateľ", "auto", "železo", "byt", "kocka", "dáma",
    "zem", "autor", "ceduľa", "čižma"];

sort($words, SORT_LOCALE_STRING);

echo "Ascending order: \n";

foreach ($words as $w) {
    echo "$w ";
}

echo "\n";

rsort($words, SORT_LOCALE_STRING);

echo "Descending order: \n";

foreach ($words as $w) {
    echo "$w ";
}

echo "\n";

我们有一个斯洛伐克语单词数组,其中包含特定的重音。

setlocale(LC_ALL, 'sk_SK.utf8');

我们使用 setlocale 函数设置斯洛伐克语区域设置。区域设置代表一个特定的地理、政治或文化区域。

$words = [ "ďateľ", "auto", "železo", "byt", "kocka", "dáma",
    "zem", "autor", "ceduľa", "čižma"];

$words 是一个带重音的斯洛伐克语单词数组。

sort($words, SORT_LOCALE_STRING);

我们使用 sort 函数按升序对数组进行排序。我们向该函数传递 SORT_LOCALE_STRING 标志,它告诉 sort 考虑区域设置。

$ php locale_sort.php
Ascending order:
auto autor byt ceduľa čižma dáma ďateľ kocka zem železo
Descending order:
železo zem kocka ďateľ dáma čižma ceduľa byt autor auto

这些单词根据斯洛伐克语标准正确排序。

有时我们需要执行自定义排序。对于自定义排序,我们在 PHP 中有 usort 函数。

custom_sorting.php
<?php

$names = [ "Michael Brown", "Albert Einstein", "Gerry Miller",
    "Tom Willis", "Michael Gray", "Luke Smith" ];

function sort_second_names($a, $b) {

    $name1 = explode(" ", $a);
    $name2 = explode(" ", $b);

    return strcmp($name1[1], $name2[1]);
}

usort($names, 'sort_second_names');

foreach ($names as $name) {
    echo "$name\n";
}

echo "\n";

我们有一个全名数组。sort 函数将根据名字对这些字符串进行排序,因为它们位于姓氏之前。我们创建一个解决方案,以便根据它们的姓氏对这些名称进行排序。

function sort_second_names($a, $b) {

    $name1 = explode(" ", $a);
    $name2 = explode(" ", $b);

    return strcmp($name1[1], $name2[1]);
}

我们有一个自定义排序函数。名称由 explode 函数拆分,并且使用 strcmp 函数比较姓氏。

usort($names, 'sort_second_names');

usort 函数接受比较函数作为其第二个参数。

$ php custom_sorting.php
Michael Brown
Albert Einstein
Michael Gray
Gerry Miller
Luke Smith
Tom Willis

这些名称根据它们的姓氏正确排序。

PHP 计算数组中的值

count 函数计算数组中元素的数量。array_sum 函数计算所有值的总和。array_product 函数计算数组中值的乘积。

counting.php
<?php

$numbers = [ 1, 2, 4, 5, 2, 3, 5, 2 ];

$len = count($numbers);
$sum = array_sum($numbers);
$prod = array_product($numbers);

echo "In the array, there are $len numbers\n";
echo "The sum of the numbers is $sum\n";
echo "The product of the numbers is $prod\n";

在这个例子中,我们有一个数字数组。我们将上述定义的函数应用于该数组。

$ php counting.php
In the array, there are 8 numbers
The sum of the numbers is 24
The product of the numbers is 2400

PHP 唯一值

在下面的例子中,我们找出数组中的唯一值。

unique.php
<?php

$numbers = array(3, 4, 4, 3, 2, 4);
$count_values = array_count_values($numbers);

print_r($count_values);

$unique = array_unique($numbers);

print_r($unique);

在这个脚本中,数组中有重复项。array_count_values 函数返回一个数组,其中包含每个值的出现次数。array_unique 函数返回一个没有重复项的数组。

$ php unique.php
Array
(
    [3] => 2
    [4] => 3
    [2] => 1
)
Array
(
    [0] => 3
    [1] => 4
    [4] => 2
)

第一个数组表示 3 出现两次,4 出现三次,2 出现一次。第二个数组表示数组中有三个值:3、4 和 2。值 3 的索引为 0,4 的索引为 1,2 的索引为 4。array_unique 函数保持索引不变。

PHP 切片数组

array_slice 函数根据其偏移量和长度参数,从数组中返回一系列元素。

slicing.php
<?php

$nums = range(1, 20);

$slice1 = array_slice($nums, 0, 3);

echo "Slice1:\n";

foreach ($slice1 as $s) {

    echo "$s ";
}

echo "\n";

$slice2 = array_slice($nums, -3);

echo "Slice2:\n";

foreach ($slice2 as $s) {

    echo "$s ";
}

echo "\n";

在这个例子中,我们创建了整数数组的两个切片。

$slice1 = array_slice($nums, 0, 3);

我们创建一个从第一个元素开始的切片;切片的长度是三个元素。

$slice2 = array_slice($nums, -3);

通过给出负偏移量,从数组的末尾创建切片。

$ php slicing.php
Slice1:
1 2 3
Slice2:
18 19 20

PHP 数组指针

PHP 有一个内部数组指针。在下面的例子中,我们介绍了操作此指针的函数。

array_pointer.php
<?php

$continents = [ "America", "Africa", "Europe", "Asia", "Australia",
    "Antarctica" ];

$item1 = current($continents);
$item2 = next($continents);
$item3 = next($continents);
$item4 = end($continents);
$item5 = prev($continents);

echo "$item1, $item2, $item3, $item4, $item5\n";

reset($continents);

while(list($idx, $val) = each($continents)) {

    echo "Index: $idx, Value: $val\n";
}

在这个例子中,我们使用移动内部数组指针的函数来遍历数组。

$item1 = current($continents);
$item2 = next($continents);
$item3 = next($continents);
$item4 = end($continents);
$item5 = prev($continents);

current 函数返回数组中的当前元素。开始时,它是数组的第一个元素。next 函数将指针向前移动一个位置。end 函数返回最后一个元素。prev 元素返回当前元素前一个位置的元素。在我们的例子中,它是倒数第二个元素。

reset($continents);

while(list($idx, $val) = each($continents)) {

    echo "Index: $idx, Value: $val\n";
}

在这里,我们使用 reset 函数再次将内部指针设置为第一个元素,并再次遍历 $continents 数组。

$ php array_pointer.php
America, Africa, Europe, Antarctica, Australia
Index: 0, Value: America
Index: 1, Value: Africa
Index: 2, Value: Europe
Index: 3, Value: Asia
Index: 4, Value: Australia
Index: 5, Value: Antarctica

PHP 合并数组

array_merge 函数合并数组。

merge.php
<?php

$names1 = [ "Jane", "Lucy", "Rebecca" ];
$names2 = [ "Lenka", "Timea", "Victoria" ];

$names = array_merge($names1, $names2);

foreach ($names as $name) {

    echo "$name ";
}

echo "\n";

在这个例子中,我们有两个数组:$names1$names2。我们使用 array_merge 函数通过合并前两个数组来创建 $names 数组。

$ php merge.php
Jane Lucy Rebecca Lenka Timea Victoria

新数组有六个名字。

PHP 修改数组

可以使用 array_pusharray_poparray_shiftarray_unshift 函数修改 PHP 数组。

modify.php
<?php

$numbers = [ 1, 2, 3, 4 ];

array_push($numbers, 5, 6);

foreach ($numbers as $num) {
    echo $num, " ";
}

echo "\n";

array_pop($numbers);

foreach ($numbers as $num) {
    echo $num, " ";
}

echo "\n";

array_unshift($numbers, -1, 0);

foreach ($numbers as $num) {
    echo $num, " ";
}

echo "\n";

array_shift($numbers);

foreach ($numbers as $num) {
    echo $num, " ";
}

echo "\n";

在上面的脚本中,我们使用修改数组内容的函数。我们有一个 $numbers 数组,它有 4 个数字:1、2、3 和 4。

array_push($numbers, 5, 6);

array_push 函数将一个或多个项目插入到数组的末尾。我们的数组现在包含值 1、2、3、4、5 和 6。

array_pop($numbers);

array_pop 函数从数组中删除最后一个项目。我们的数组现在存储数字 1、2、3、4 和 5。

array_unshift($numbers, -1, 0);

array_unshift 函数在数组的开头添加 -1 和 0。数组包含值 -1、0、1、2、3、4 和 5。

array_shift($numbers);

最后,array_shift 函数从数组中删除第一个项目。现在我们在数组中有值 0、1、2、3、4 和 5。

$ php modify.php
1 2 3 4 5 6
1 2 3 4 5
-1 0 1 2 3 4 5
0 1 2 3 4 5

PHP range 函数

range 函数通过自动创建一个元素序列来简化数组创建。它接受三个参数:序列的开始、序列的结束和一个可选的增量,默认为 1。

range.php
<?php

$numbers1 = range(1, 15);

foreach ($numbers1 as $num) {
    echo "$num ";
}

echo "\n";

$numbers2 = range(15, 1, -1);

foreach ($numbers2 as $num) {
    echo "$num ";
}

echo "\n";

range 函数使我们能够轻松地创建一系列连续的数字。

$numbers1 = range(1, 15);

创建了一个包含数字 1、2、... 15 的数组。

$numbers2 = range(15, 1, -1);

可以通过指定负增量来创建值的降序序列。

$ php range.php
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
15 14 13 12 11 10 9 8 7 6 5 4 3 2 1

PHP 随机化数组值

array_rand 函数从数组中选择一个或多个随机条目。shuffle 函数随机化数组中元素的顺序。

randomize.php
<?php

$nums = range(1, 20);

echo ($nums[array_rand($nums)]) . "\n";

$r = array_rand($nums, 2);
echo $nums[$r[0]] . "\n";
echo $nums[$r[1]] . "\n";

shuffle($nums);

foreach ($nums as $n) {
    echo "$n ";
}

echo "\n";

在这个例子中,我们从数组中选择随机值并随机化其元素的顺序。

echo ($nums[array_rand($nums)]) . "\n";

array_rand 函数从 $num 数组中返回一个随机键。

$r = array_rand($nums, 2);

在这种情况下,array_rand 函数返回一个包含两个随机键的数组。

$ php randomize.php
4
2
19
13 19 4 3 17 11 20 16 10 9 8 14 15 12 18 2 6 5 1 7

这是 randomize.php 程序的示例输出。

PHP in_array 函数

in_array 函数检查数组中是否存在特定元素。

inarray.php
<?php

$names = [ "Jane", "Adriana", "Lucy", "Rebecca" ];

if (in_array("Jane", $names)) {
    echo "Jane is in the array\n";
} else {
    echo "Jane is not in the array\n";
}

if (in_array("Monica", $names)) {
    echo "Monica is in the array\n";
} else {
    echo "Monica is not in the array\n";
}

我们的脚本检查 'Jane' 和 'Monica' 是否在 $names 数组中。

$ php inarray.php
Jane is in the array
Monica is not in the array

“Jane” 在数组中,但“Monica”不在。

PHP 数组键和值

PHP 数组是一个关联数组,它由键和值对组成。

keysvalues.php
<?php

$domains = [ "sk" => "Slovakia", "de" => "Germany",
    "hu" => "Hungary", "ru" => "Russia" ];

$keys = array_keys($domains);
$values = array_values($domains);

foreach ($keys as $key) {
    echo "$key ";
}

echo "\n";

foreach ($values as $value) {
    echo "$value ";
}

echo "\n";

array_keys 函数返回数组的所有键。array_values 函数返回数组的所有值。

$ php keysvalues.php
sk de hu ru
Slovakia Germany Hungary Russia

第一行包含顶级域名。这些是 $domains 数组的键。第二行是相应国家/地区的名称。这些是数组的值。

PHP array_walk 函数

array_walk 函数将用户定义的函数应用于数组的每个成员。

array_walk.php
<?php

$countries = [ "de" => "Germany", "sk" => "Slovakia",
    "us" => "United States", "ru" => "Russia",
    "hu" => "Hungaria", "pl" => "Poland" ];

function show_values($value, $key) {

    echo "The $key stands for the $value\n";
}

array_walk($countries, 'show_values');

我们有一个 $countries 数组。我们将 show_values 函数应用于数组的每个元素。该函数只是打印每个元素的键和值。

$ php array_walk.php
The de stands for the Germany
The sk stands for the Slovakia
The us stands for the United States
The ru stands for the Russia
The hu stands for the Hungaria
The pl stands for the Poland

来源

PHP 数组 - 语言参考

在本文中,我们介绍了 PHP 数组。

作者

我叫 Jan Bodnar,是一位充满激情的程序员,拥有丰富的编程经验。自 2007 年以来,我一直在撰写编程文章。到目前为止,我撰写了 1,400 多篇文章和 8 本电子书。我拥有超过十年的编程教学经验。

列出所有 PHP 教程。