2

I have a PHP array with say 50 items in it. I then use array_slice to extract 12 items:

$extractItems = array_slice($rows,0,12);

I then use the $extractItems and this is fine.

The catch is I want to then write the remaining items (eg: $rows - $extractItems) to cache.

When I view $rows I can see array_slice doesn't remove the items. Just copies a section to a new array.

How would I best get a set of the items not 'array_sliced'?

thankyou :)

2 Answers 2

5

You could use array_splice instead. This would remove the first 12 items from $rows

$extractedItems = array_splice($rows, 0, 12);
// $rows now equals $rows - $extractedItems

A quick demo

php > $rows = [1,2,3,4,5,6];
php > $extractedItems = array_splice($rows, 0, 2);
php > var_dump($extractedItems, $rows);
array(2) {
  [0]=>
  int(1)
  [1]=>
  int(2)
}
array(4) {
  [0]=>
  int(3)
  [1]=>
  int(4)
  [2]=>
  int(5)
  [3]=>
  int(6)
}
Sign up to request clarification or add additional context in comments.

2 Comments

+1. I don't particularly like mutable arrays, but it can sometimes come in handy :)
@Jack Yeah, I considered that too but it seemed to match the OP's requirements
5

You can get the rest of the items by slicing from index 12 onwards:

array_slice($rows, 12);

This is similar to how substr($str, $index) works.

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.