0

I'd like to use an array_slice to get every value in an array iterated over, except for the current one, the one before it, and all the others until the end of the array.

So for example, say I have 5 elements:

[1, 2, 3, 4, 5]

I want a way for a condition to fire on 3, cut it out, and then also cut out 4 and 5. I have this, but I don't think it's correct:

$items = array_slice($items, $itemcount - 1);
4
  • $itemcount is an iterating number that goes up with each instance of the loop. Commented Jan 21, 2014 at 16:17
  • 1
    So what do you get as result and what are you expecting? Commented Jan 21, 2014 at 16:18
  • Oh wait, I'd want $items = array_slice($items, 0, $itemcount - 1);, wouldn't I? Commented Jan 21, 2014 at 16:22
  • @AndrewAlexander what do you mean by "cut it out?" You want these to be removed from the array permanently? Commented Jan 21, 2014 at 16:27

1 Answer 1

2

array_slice() returns the sequence of elements from the array array as specified by the offset and length parameters.

So if you want to get the 3,4,5 your offset should be 2, because the array key ( starts from 0 ex: 0,1,2,3,4). i didn't use length in this one because i want to get it till the end (5)

$items = array_slice($items, 2);

If you want to grag 1,2 it should be like this. ( i use length 2 because i want to get the first 2 keys)

$items = array_slice($items, 0, 2);

Example

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.