0

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?

2
  • 3
    The third argument to array_slice() is the length of the slice, not the end index. Commented Nov 3, 2013 at 21:13
  • Thanks a lot Barmar, I didn't understand it the right way, it works perfectly now :) Commented Nov 3, 2013 at 21:15

1 Answer 1

1

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

Demo!

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.