【问题标题】:How to remove the nth element from the end of an array如何从数组末尾删除第n个元素
【发布时间】:2020-10-01 09:09:48
【问题描述】:

我知道您可以使用“array_pop”来删除数组中的最后一个元素。但如果我想删除最后 2 或 3 个,我会怎么做?

那么我将如何删除该数组中的最后 2 个元素?

<?php
$stack = array("orange", "banana", "apple", "raspberry");
$fruit = array_pop($stack);
print_r($stack);
?>

【问题讨论】:

    标签: php arrays


    【解决方案1】:

    使用array_splice 并指定要删除的元素数量。

    $stack = array("orange", "banana", "apple", "raspberry");
    $fruit = array_splice($stack, -2);
    print_r($stack);
    

    输出

    数组

    (
        [0] => orange
        [1] => banana
    )
    

    【讨论】:

      【解决方案2】:

      您可以将array_slice() 与否定的length 一起使用:

      function array_remove($array, $n) {
          return array_slice($array, 0, -$n);
      }
      

      测试:

      print_r( array_remove($stack, 2) );
      

      输出:

      Array
      (
          [0] => orange
          [1] => banana
      )
      

      【讨论】:

        【解决方案3】:

        为了删除该数组的最后 2 个元素,您应该以这种方式使用 array_slice:

        $fruits = array_slice($stack, 0, -2);

        【讨论】:

          【解决方案4】:

          正如韵律所说:pop 两次,或者 array_slice!

          换句话说:http://php.net/array_slice

          【讨论】:

            【解决方案5】:

            您可以只使用 array_pop() 两次。像这样运行它:

            <?php
            $stack = array("orange", "banana", "apple", "raspberry");
            array_pop($stack);
            array_pop($stack);
            print_r($stack);
            ?>
            

            输出:

            (
                [0] => orange
                [1] => banana
            )
            

            array_pop() 的返回值是你刚刚删除的元素,不是数组。因此,如果您不再需要该元素,只需根据需要多次调用该函数并继续。

            【讨论】:

              猜你喜欢
              • 1970-01-01
              • 1970-01-01
              • 2014-11-04
              • 2012-12-02
              • 2016-03-30
              • 1970-01-01
              • 2023-01-28
              • 2015-02-10
              • 1970-01-01
              相关资源
              最近更新 更多