PHP中的弹出和移动数组。什么时候使用每一种方法

138 阅读2分钟

PHP有很多内置的数组函数来帮助完成许多常见的任务。不过,这么多函数的存在也会让人有点不知所措,因为有时要记住这些函数之间的细微差别。

也有可能使用几个函数的不同组合来实现同样的事情。这意味着,对这些函数有一个清晰的了解,将有助于你用更少的行数写出性能更好的代码。

在这篇文章中,你将了解到PHP中的array_pop()array_shift() 函数。

用PHP弹出数组

有一个专门的函数叫array_pop() ,可以帮助你在PHP中从一个给定的数组的末端弹出一个元素。它做了三件事。

  1. 返回数组中最后一个元素的值。
  2. 将数组缩短一个元素。
  3. 重新设置指定数组的指针。

下面是array_pop() 函数的一个例子。

<?php

$people = ["Adam", "Andrew", "Monty", "Sajal"];

while(count($people)) {
    echo array_pop($people)." ";
}
// Output: Sajal Monty Andrew Adam 

?>

你可以将array_pop()end()key() 结合使用,以便从一个数组中获得最后一个键值对。这里有一个假设的例子,我们要给不同的人送一堆东西。

<?php

$deliveries = ["Adam" => "LED TV", "Andrew" => "Drone", "Monty" => "Smart watch", "Sajal" => "Laptop"];

while(count($deliveries)) {
    end($deliveries);
    $person = key($deliveries);
    $item = array_pop($deliveries);

    // call delivered($item, $person);
    echo "Delivered ".$item." to ".$person.".\n";
}

/*
Delivered Laptop to Sajal.
Delivered Smart watch to Monty.
Delivered Drone to Andrew.
Delivered LED TV to Adam.
*/

?>

我们使用end() ,将数组指针移到最后一个元素。key() 函数帮助我们获得人的名字,array_pop() 获得物品的名字,同时将其从数组中删除。

当你想实现LIFO或Last In First Out系统时,array_pop() 函数很有用。当你处理一堆元素,并想在访问最后一个元素的同时把它从数组中删除时,你应该考虑使用它。

用PHP移位数组

array_shift() 函数将把一个元素从数组的起点移开。它对你的数组做了以下工作。

  1. 返回数组的第一个元素。
  2. 将数组缩短一个元素。
  3. 数字键被重新索引,而文字键则不被触动。
  4. 重新设置指定数组的指针。

下面是array_shift() 函数的一个例子。你可以看到数字键已经通过从零开始计数而被重新索引了。

<?php

$people = ["Adam", "Andrew", "Monty", "Sajal"];

var_dump($people);
/*
array(4) {
  [0]=>
  string(4) "Adam"
  [1]=>
  string(6) "Andrew"
  [2]=>
  string(5) "Monty"
  [3]=>
  string(5) "Sajal"
}
*/

while(count($people)) {
    echo array_shift($people)."\n";
    if(count($people) == 2) {
        var_dump($people);
    }
}

/*
Adam
Andrew

array(2) {
  [0]=>
  string(5) "Monty"
  [1]=>
  string(5) "Sajal"
}

Monty
Sajal
*/


?>

通过使用key()array_shift() 的组合,你可以在PHP中从一个关联数组中获得键值对。不需要改变内部数组的指针,因为array_shift() 会自动为你做这件事。

<?php

$orders = ["Adam" => "Pizza", "Andrew" => "Coffee", "Monty" => "Taco", "Sajal" => "Lemonade"];

while(count($orders)) {
    $person = key($orders);
    $food = array_shift($orders);

    // call served($food, $person);
    echo "Served ".$food." to ".$person.".\n";
}
/*
Served Pizza to Adam.
Served Coffee to Andrew.
Served Taco to Monty.
Served Lemonade to Sajal.
*/

?>

当你想实现FIFO或先进先出系统时,array_shift() 函数很有用。在我们上面的例子中,我们模拟了一个系统,在这个系统中,餐厅的食物订单是根据谁先点的来提供给顾客。

最后的思考

在本教程中,你学到了如何使用PHP中的array_pop()array_shift() 函数来获得数组的最后一个或第一个元素。你也可以使用end()key() 这些函数来从一个关联数组中获得键值对。当处理非常大的数组时,array_shift() 的性能会很慢。在这种情况下,你可能想使用array_reverse() ,然后再使用array_pop()