0

I have an array with of enumerating numbers, like:

$pageNumbers = array(1,2,3,4,5,6,7,8,9,10);

Now I have an active page number $currentPage and want to have based on this, before and after 2 elements - a total number of 5.

$currentPage = 2:

Return: array(1,2,3,4,5)

$currentPage = 6

Return: array(4,5,6,7,8)

$currentPage = 10

Return: array(6,7,8,9,10)

Unfortunately, I did not come up with an elegant and simple method to solve this (2x while, 1 big foreach and so on). Maybe you have an idea.

My first idea was:

foreach ($pageNumbers as $page) {
        if($page < $currentPage+3 && $page > $currentPage-3) {
            array_push(...);
        }
    }

This will work for the $currentPage = 6, but if $currentPage = 1, it will only return 1,2,3.

5
  • nevertheless, please show what you've got. Was is working? What was the problem? Commented Nov 5, 2018 at 16:55
  • array_search and array_splice would work fine. Commented Nov 5, 2018 at 16:57
  • Have you considered to find the index of the current page and then trimming the array either side? Commented Nov 5, 2018 at 16:57
  • Thanks @Jeff, I added my tryout. Commented Nov 5, 2018 at 17:01
  • range($start,$end) and then a tiny bit of math and some checks for first and last page, Commented Nov 5, 2018 at 17:01

1 Answer 1

2

Use array_slice and cut out the part of the array you need.

I use an if to see where to slice the array.

if($currentPage < 3){
    $arr = array_slice($pageNumbers,0,5);
}elseif($currentPage > count($pageNumbers)-2){
    $arr = array_slice($pageNumbers,-5,5);
}else{
    $arr = array_slice($pageNumbers,$currentPage-3,5);
}

See working example below.
https://3v4l.org/fpOFQ

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.