views:

343

answers:

6

Hi,

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'
+3  A: 

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.

ryeguy
Wouldn't it be better to use -1 instead of count($input)-2 ?
Jeriko
Yeah, I didn't notice that at first. Fixed.
ryeguy
+1  A: 
array_pop($array); // remove the last element
array_shift($array); // remove the first element
MDCore
+9  A: 

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.

Decko
+1  A: 

To remove first elemnt, use array_shift, to remove last, use array_pop:

<?php    
$array = array('10', '20', '30.30', '40', '50');
array_shift($array);
array_pop($array);
Janci
+1  A: 

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 :)

Jeriko
+2  A: 

Check this code:

$arry = array('10', '20', '30.30', '40', '50');
$fruit = array_shift($arry);
$fruit = array_pop($arry);
print_r($arry);
Karthik