I've been recently working with the array_slice function in order to make pagination in my script.
I have an array with 40 values (each value is a thread)
$thread_order_P = $this->forum_handler->orderThreads($forum_threads);
And I want to show only 15 threads a page so I did the following :
$cu_page = $_GET['page'];
$threads_per_page = 15;
$start_f_value = $cu_page-1;
$start_f_value = $start_f_value*$threads_per_page;
$end_f_value = $threads_per_page*$cu_page;
$thread_order = array_slice($thread_order_P, $start_f_value, $end_f_value);
Now, the thing is when I try to display page 1 [echos 15 threads] and 3[echos 10 threads] it works pefectly, but when I try to display page 2 it echos 25 threads instead of 15..
Any ideas?
As Barmar pointed out in the comments, the third argument to array_slice()
is the length of the slice, not the end index.
From the array_slice()
documentation:
If length is given and is positive, then the sequence will have up to that many elements in it. If the array is shorter than the length, then only the available array elements will be present. If length is given and is negative then the sequence will stop that many elements from the end of the array. If it is omitted, then the sequence will have everything from offset up until the end of the array.
So, change your array_slice()
statement to the following:
$thread_order = array_slice($thread_order_P, $start_f_value, $threads_per_page);