In PHP, how do I paginate arrays with PHP 8+ features?

In PHP 8 and above, you can easily paginate arrays using modern language features like union types, named arguments, and the new `match` expression. Below is an example of how to paginate an array of items.

PHP pagination, array pagination, PHP 8 features, efficient data handling, PHP examples

This example demonstrates how to paginate an array in PHP 8+ using modern syntax and features to produce readable and maintainable code.


     1,
            $currentPage > $totalPages => $totalPages,
            default => $currentPage,
        };

        $offset = ($currentPage - 1) * $itemsPerPage;

        // Slice the array to get the appropriate page
        return array_slice($items, $offset, $itemsPerPage);
    }

    // Sample data
    $data = range(1, 100); // An array of numbers from 1 to 100

    // Get current page from request (default to 1 if not set)
    $currentPage = $_GET['page'] ?? 1;
    
    // Paginate
    $paginatedData = paginateArray($data, (int)$currentPage, 10);

    // Display the paginated data
    echo '<pre>';
    print_r($paginatedData);
    echo '</pre>';
    ?>
    

PHP pagination array pagination PHP 8 features efficient data handling PHP examples