当前位置: 动力学知识库 > 问答 > 编程问答 >

PHP: Remove the first and last item of the array

问题描述:

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'

网友答案:

Using array_slice is simplest

$newarray = array_slice($array, 1, -1);

If the input array has less than 3 elements in it, the output array will be empty.

网友答案:

To remove the first element, use array_shift, to remove last element, use array_pop:

<?php    
$array = array('10', '20', '30.30', '40', '50');
array_shift($array);
array_pop($array);
网友答案:
array_pop($array); // remove the last element
array_shift($array); // remove the first element
网友答案:

array_slice is going to be the fastest since it's a single function call.

You use it like this: array_slice($input, 1, -1);

Make sure that the array has at least 2 items in it before doing this, though.

网友答案:

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_pop and array_slice documentation :)

网友答案:

Check this code:

$arry = array('10', '20', '30.30', '40', '50');
$fruit = array_shift($arry);
$fruit = array_pop($arry);
print_r($arry);
网友答案:
<?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>";
}   
?>
分享给朋友:
您可能感兴趣的文章:
随机阅读: