php简单数组

php by 黄业兴 at 2020-04-15

数组是一种特殊类型的变量,可以包含许多变量,并将它们保存在列表中。

例如,假设我们要创建一个包含1到10之间的所有奇数的列表。创建列表后,我们可以使用变量的索引分配新变量,该变量将引用数组中的变量。

要使用列表中的第一个变量(在本例中为数字1),我们将需要给出第一个索引(即0),因为PHP使用的是从零开始的索引,就像今天几乎所有编程语言一样。

$odd_numbers = [1,3,5,7,9];
$first_odd_number = $odd_numbers[0];
$second_odd_number = $odd_numbers[1];

echo "The first odd number is $first_odd_number\n";
echo "The second odd number is $second_odd_number\n";

现在,我们可以使用索引添加新变量。要将项目添加到列表的末尾,我们可以为数组分配索引5(第6个变量):

$odd_numbers = [1,3,5,7,9];
$odd_numbers[5] = 11;
print_r($odd_numbers);

根据需要,数组可以包含不同类型的变量,甚至可以包含其他数组或对象作为成员。

要从数组中删除项目,请使用unset成员本身上的函数。例如:

$odd_numbers = [1,3,5,7,9];
unset($odd_numbers[2]); // will remove the 3rd item (5) from the list
print_r($odd_numbers);

有用的功能 该count函数返回数组具有的成员数。

$odd_numbers = [1,3,5,7,9];
echo count($odd_numbers);

该reset函数获取数组的第一个成员。(它还会重置内部迭代指针)。

$odd_numbers = [1,3,5,7,9];
$first_item = reset($odd_numbers);
echo $first_item;

我们还可以使用索引语法来获取数组的第一个成员,如下所示:

$odd_numbers = [1,3,5,7,9];
$first_item = $odd_numbers[0];
echo $first_item;

该end函数获取数组的最后一个成员。

$odd_numbers = [1,3,5,7,9];
$last_item = end($odd_numbers);
echo $last_item;

我们还可以使用该count函数获取列表中元素的数量,然后使用它来引用数组中的最后一个变量。请注意,我们从最后一个索引中减去1,因为在PHP中索引是从零开始的,因此我们需要解决以下事实:我们不计算变量号零。

$odd_numbers = [1,3,5,7,9];
$last_index = count($odd_numbers) - 1;
$last_item = $odd_numbers[$last_index];
echo $last_item;

堆栈和队列功能 数组也可以用作堆栈和队列。

要将成员推到数组的末尾,请使用以下array_push函数:

$numbers = [1,2,3];
array_push($numbers, 4); // now array is [1,2,3,4];

// print the new array
print_r($numbers);

要从数组末尾弹出成员,请使用以下array_pop函数:

$numbers = [1,2,3,4];
array_pop($numbers); // now array is [1,2,3];

// print the new array
print_r($numbers);

要将成员推到数组的开头,请使用以下array_unshift函数:

$numbers = [1,2,3];
array_unshift($numbers, 0); // now array is [0,1,2,3];

// print the new array
print_r($numbers);

要从数组的开头弹出成员,请使用以下array_shift函数:

$numbers = [0,1,2,3];
array_shift($numbers); // now array is [1,2,3];

// print the new array
print_r($numbers);

串联数组 我们可以使用array_merge来连接两个数组:

$odd_numbers = [1,3,5,7,9];
$even_numbers = [2,4,6,8,10];
$all_numbers = array_merge($odd_numbers, $even_numbers);
print_r($all_numbers);

排序数组 我们可以使用该sort函数对数组进行排序。该rsort函数对数组进行反向排序。请注意,排序是在输入数组上完成的,并且不会返回新数组。

$numbers = [4,2,3,1,5];
sort($numbers);
print_r($numbers);

先进的阵列功能 该array_slice函数返回一个新数组,该数组包含从偏移量开始的特定数组的特定部分。例如,如果我们要丢弃数组的前三个元素,则可以执行以下操作:

$numbers = [1,2,3,4,5,6];
print_r(array_slice($numbers, 3));

我们还可以决定采取特定长度的切片。例如,如果我们只想取两个项目,则可以向该函数添加另一个参数:

$numbers = [1,2,3,4,5,6];
print_r(array_slice($numbers, 3, 2));

该array_splice函数的作用完全相同,但是它也会删除从原始数组返回的切片(在这种情况下为numbers变量)。

$numbers = [1,2,3,4,5,6];
print_r(array_splice($numbers, 3, 2));
print_r($numbers);

请关注我们微信公众号:mw748219