Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP array_slice - how get original array without sliced items

Tags:

arrays

php

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

like image 240
Adam Avatar asked Mar 31 '26 13:03

Adam


2 Answers

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)
}
like image 99
Phil Avatar answered Apr 03 '26 03:04

Phil


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.

like image 42
Ja͢ck Avatar answered Apr 03 '26 01:04

Ja͢ck



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!