U
U
Uzair Izha2015-11-17 12:10:59
PHP
Uzair Izha, 2015-11-17 12:10:59

I can’t display array elements in the loop in between, how to build a loop correctly?

At first, from 0 to 5 elements are displayed for me.
Then, according to the idea, from 5 to 10 elements are displayed, but from 0 to 10, what is the error?

for ($x=0, $i=0, $d=5; $i <= $_REQUEST['count']; $i++, $x+=5, $d+=5) {
  if($_GET['page']==$i) {
    $rea = array_slice($new_arr, $x, $d);
  }
}

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Alex Safonov, 2015-11-17
@UZEIR

Specifically, the error in your code is the third argument to the array_slice() function . The third argument is not the final offset, but the number of elements counting from the value of the second argument.
That is, change it to something like this:
But I would prefer not to waste for . Add filtering and sanitizing input parameters.

$new_arr = range(1, 200);

$page              = (int)$_GET['page'] - 1;//logically we have page 0, but UI will show page 1
$count             = (int)$_GET['count'];
$count             = ($count > 0 && $count<=50)$count?50;
$startElementIndex = $page * $count;

$rea = array_slice($new_arr, $startElementIndex, $count);

var_dump($rea);

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question