Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

array_slice with negative offset on huge arrays

Tags:

arrays

php

For reason that I'll not discuss here, I'm forced to parse a large directory of files (we are talking 100.000 < x < 1.000.000+) and return the filelist as an array.

I'm already caching the file list, the problem is array_slice.

Yes, because there is a catch, this list of file must be "paginated" returning them in block of 16.

What I'm doing is this:

$items_per_page = 16;
$offset = ($current_page * $items_per_page) + $items_per_page;
array_slice($array,-$offset,$items_per_page);

It's easy to see that in a few pages we'll have huge offsets. Also starting from page four (offset = -80) there is a huge performance hit.

What could I use instead of array_slice to achieve this sort of array pagination?

Thanks

like image 413
0plus1 Avatar asked May 27 '11 14:05

0plus1


People also ask

Can a PHP array have a negative index?

An array, in PHP, is actually just some kind of an ordered map : you can use integers (positive or negative), but also strings, as keys -- and there will not be much of difference.

What are the parameters required in array_slice?

Parameters: This function can take four parameters and are described below: $array (mandatory): This parameter refers to the original array, we want to slice. $start_point (mandatory): This parameter refers to the starting position of the array from where the slicing need to be performed.

What does array_ slice do in php?

The array_slice() function returns selected parts of an array. Note: If the array have string keys, the returned array will always preserve the keys (See example 4).


1 Answers

Consider creating, filling and manipulating a DB table instead of doing all of this in memory. An index on it will allow you to paginate the files with reasonable performance.

like image 168
Denis de Bernardy Avatar answered Sep 28 '22 03:09

Denis de Bernardy