PHP:删除数组的第一项和最后一项
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2675257/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
PHP: Remove the first and last item of the array
提问by Janci
Suppose I have this array:
假设我有这个数组:
$array = array('10', '20', '30.30', '40', '50');
Questions:
问题:
What is the fastest/easiest way to remove the first item from the above array?
What is the fastest/easiest way to remove the last item from the above array?
从上述数组中删除第一项的最快/最简单的方法是什么?
从上述数组中删除最后一项的最快/最简单的方法是什么?
So the resulting array contains only these values:
所以结果数组只包含这些值:
- '20'
- '30.30'
- '40'
- '20'
- '30.30'
- '40'
回答by Decko
Using array_slice is simplest
使用 array_slice 是最简单的
$newarray = array_slice($array, 1, -1);
If the input array has less than 3 elements in it, the output array will be empty.
如果输入数组中的元素少于 3 个,则输出数组将为空。
回答by Janci
To remove the first element, use array_shift, to remove last element, use array_pop:
要删除第一个元素,请使用array_shift,要删除最后一个元素,请使用array_pop:
<?php
$array = array('10', '20', '30.30', '40', '50');
array_shift($array);
array_pop($array);
回答by MDCore
array_pop($array); // remove the last element
array_shift($array); // remove the first element
回答by Karthik
Check this code:
检查此代码:
$arry = array('10', '20', '30.30', '40', '50');
$fruit = array_shift($arry);
$fruit = array_pop($arry);
print_r($arry);
回答by ryeguy
array_sliceis going to be the fastest since it's a single function call.
array_slice将是最快的,因为它是单个函数调用。
You use it like this:
array_slice($input, 1, -1);
你像这样使用它:
array_slice($input, 1, -1);
Make sure that the array has at least 2 items in it before doing this, though.
不过,在执行此操作之前,请确保数组中至少有 2 个项目。
回答by Jeriko
Removes the first element from the array, and returns it:
从数组中删除第一个元素,并返回它:
array_shift($array);
Removes the last element from the array, and returns it:
从数组中删除最后一个元素,并返回它:
array_pop($array);
If you dont mind doing them both at the same time, you can use:
如果您不介意同时执行它们,则可以使用:
array_shift($array,1,-1));
to knock off the first and last element at the same time.
同时敲除第一个和最后一个元素。
Check the array_push, array_popand array_slicedocumentation :)
检查array_push,array_pop和array_slice文档:)
回答by kdniazi
<?php
$array = array("khan","jan","ban","man","le");
$sizeof_array = sizeof($array);
$last_itme = $sizeof_array-1;
//$slicearray= array_slice($array,'-'.$sizeof_array,4);// THIS WILL REMOVE LAST ITME OF ARRAY
$slicearray = array_slice($array,'-'.$last_itme);//THIS WILL REMOVE FIRST ITEM OF ARRAY
foreach($slicearray as $key=>$value)
{
echo $value;
echo "<br>";
}
?>

