tags:

views:

45

answers:

1

I have a need to get the last 6 values from an multidimentional array, I was trying to do something like this

for($i=0;$i<6;$i++){
        $stats = array_shift($stats);
}

But then after the first array_shift I get the following error

PHP Warning:  array_shift(): The argument should be an array

Are there any functions that could do this in PHP

+8  A: 

You can use array_slice():

$stats = array_slice($stats, -6);

The reason your code isn't working is because

  1. array_shift() removes from the front of the array - so you'd end up with the first 6 removed, which is not the same as getting the last 6 unless your array has 12 items...
  2. array_shift edits the array in place and returns the item it removed
Greg
The second of those reasons is why you get the warning - since you've got a multi-dimensional array, the first time through the loop `array_shift` returns you the first element of your multi-dimensional array, which is a (mono-dimensional) array. Calling `array_shift` on a mono-dimensional array returns the first value of that array, so `$stats` is not an array after the second time through the loop. I'd expect you to get an error after `array_shift` has been called twice (i.e. in the 3rd iteration of the loop).
Dominic Rodger