Encodera

Thanks for reading!

Donate to the site — we work hard for you.

How to split an array into chunks

Short answer

array_chunk() splits an array into chunks of a given size:

<?php
 
echo json_encode(array_chunk([1, 2, 3, 4, 5], 2));

Output:

[[1,2],[3,4],[5]]

A single page

To take only the needed page, use array_slice():

<?php
 
$items = range(1, 25);
$page = 2;
$perPage = 10;
 
echo implode(', ', array_slice($items, ($page - 1) * $perPage, $perPage));

Output:

11, 12, 13, 14, 15, 16, 17, 18, 19, 20

The number of pages

Divide the number of elements by the page size and round up:

<?php
 
echo (int) ceil(25 / 10);

Output:

3

Functions used in this recipe

  • array_chunk — Splits an array into chunks of a given size.
  • array_slice — Returns part of an array.
  • ceil — Rounds a number up to an integer.

Thanks for reading!

Donate to the site — we work hard for you.