Array (array) in PHP language is a very practical data type that can be used to store multiple data and perform batch operations. However, sometimes we need to split a large array into multiple smaller arrays for better processing. At this time, the array_chunk() in the PHP function comes in handy. This article will share how to use the array_chunk() function to perform array chunking operations and some practical tips.
1. Overview of the array_chunk() function
The array_chunk() function is to divide an array into chunks of a specified size and return a two-dimensional array. The function definition is as follows:
array array_chunk ( array $array , int $size [, bool $preserve_keys = false ] )
Parameter description:
- $array : Required, the array to be divided into blocks.
- $size: Required, an integer specifying the length of each block.
- $preserve_keys: Optional, a Boolean value indicating whether to retain the key names of the original array. The default is false, that is, not retained.
This function returns a two-dimensional array, where the length of each sub-array is $size, and the length of the last sub-array can be less than $size.
2. Example of array_chunk() function
In order to better understand the usage of array_chunk() function, we can look at the following example.
First, we define an array containing 10 elements:
<?php $arr = array('a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j'); ?>
We can use the array_chunk() function to divide it into small arrays of length 3:
<?php $result = array_chunk($arr, 3); print_r($result); ?>
Result As follows:
Array ( [0] => Array ( [0] => a [1] => b [2] => c ) [1] => Array ( [0] => d [1] => e [2] => f ) [2] => Array ( [0] => g [1] => h [2] => i ) [3] => Array ( [0] => j ) )
As you can see, the original array is divided into 4 sub-arrays with a length of 3. The last subarray has only one element because there is only one element left in the original array.
3. Practical skills of the array_chunk() function
- Array paging
We can use the array_chunk() function to paginate an array and divide each page into The number of data entries is specified as the length of each block. This is very useful for making a simple paging system. For example, we can divide a total of 50 data into 10 per page, and then display them on 5 pages.
<?php $arr = range(1,50); $pages = array_chunk($arr,10); print_r($pages); ?>
The results are as follows:
Array ( [0] => Array ( [0] => 1 [1] => 2 [2] => 3 [3] => 4 [4] => 5 [5] => 6 [6] => 7 [7] => 8 [8] => 9 [9] => 10 ) [1] => Array ( [0] => 11 [1] => 12 [2] => 13 [3] => 14 [4] => 15 [5] => 16 [6] => 17 [7] => 18 [8] => 19 [9] => 20 ) [2] => Array ( [0] => 21 [1] => 22 [2] => 23 [3] => 24 [4] => 25 [5] => 26 [6] => 27 [7] => 28 [8] => 29 [9] => 30 ) [3] => Array ( [0] => 31 [1] => 32 [2] => 33 [3] => 34 [4] => 35 [5] => 36 [6] => 37 [7] => 38 [8] => 39 [9] => 40 ) [4] => Array ( [0] => 41 [1] => 42 [2] => 43 [3] => 44 [4] => 45 [5] => 46 [6] => 47 [7] => 48 [8] => 49 [9] => 50 ) )
Each subarray contains 10 elements, just like each page contains 10 data.
- Array splitting
Suppose we have a string separated by commas, and we want to split it into an array, and split 10 elements each time, you can Use the array_chunk() function to accomplish this operation.
<?php $str = "1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20"; $arr = explode(',', $str); $result = array_chunk($arr, 10); print_r($result); ?>
The results are as follows:
Array ( [0] => Array ( [0] => 1 [1] => 2 [2] => 3 [3] => 4 [4] => 5 [5] => 6 [6] => 7 [7] => 8 [8] => 9 [9] => 10 ) [1] => Array ( [0] => 11 [1] => 12 [2] => 13 [3] => 14 [4] => 15 [5] => 16 [6] => 17 [7] => 18 [8] => 19 [9] => 20 ) )
- Array random sorting
If we want to disrupt the ordering of elements in an array, we can first use array_chunk() Divide the array into blocks, then shuffle the elements of each block, and finally connect the elements of all blocks together to complete random sorting.
<?php $arr = range(1, 20); $chunk_arr = array_chunk($arr, 5); foreach ($chunk_arr as $key => &$value) { shuffle($value); } $result = call_user_func_array('array_merge', $chunk_arr); print_r($result); ?>
The results are as follows:
Array ( [0] => 1 [1] => 4 [2] => 2 [3] => 3 [4] => 5 [5] => 9 [6] => 10 [7] => 7 [8] => 6 [9] => 8 [10] => 11 [11] => 12 [12] => 14 [13] => 13 [14] => 16 [15] => 15 [16] => 17 [17] => 20 [18] => 19 [19] => 18 )
We first divided the original array into 4 sub-arrays with a length of 5, then scrambled and sorted each sub-array, and finally used array_merge() The function merges all subarrays together, disrupting the order of the original arrays.
4. Summary
The array_chunk() function is a very practical function in the PHP language. It can help us divide a large array into multiple small arrays, providing a convenient way for logical processing. A great convenience. This article introduces the function and usage of the array_chunk() function, and shares some practical tips for array chunking. I hope this article will be helpful to learners of PHP language.
The above is the detailed content of Practical tips for PHP functions: array_chunk(). For more information, please follow other related articles on the PHP Chinese website!

Long URLs, often cluttered with keywords and tracking parameters, can deter visitors. A URL shortening script offers a solution, creating concise links ideal for social media and other platforms. These scripts are valuable for individual websites a

Laravel simplifies handling temporary session data using its intuitive flash methods. This is perfect for displaying brief messages, alerts, or notifications within your application. Data persists only for the subsequent request by default: $request-

This is the second and final part of the series on building a React application with a Laravel back-end. In the first part of the series, we created a RESTful API using Laravel for a basic product-listing application. In this tutorial, we will be dev

Laravel provides concise HTTP response simulation syntax, simplifying HTTP interaction testing. This approach significantly reduces code redundancy while making your test simulation more intuitive. The basic implementation provides a variety of response type shortcuts: use Illuminate\Support\Facades\Http; Http::fake([ 'google.com' => 'Hello World', 'github.com' => ['foo' => 'bar'], 'forge.laravel.com' =>

The PHP Client URL (cURL) extension is a powerful tool for developers, enabling seamless interaction with remote servers and REST APIs. By leveraging libcurl, a well-respected multi-protocol file transfer library, PHP cURL facilitates efficient execution of various network protocols, including HTTP, HTTPS, and FTP. This extension offers granular control over HTTP requests, supports multiple concurrent operations, and provides built-in security features.

Do you want to provide real-time, instant solutions to your customers' most pressing problems? Live chat lets you have real-time conversations with customers and resolve their problems instantly. It allows you to provide faster service to your custom

The 2025 PHP Landscape Survey investigates current PHP development trends. It explores framework usage, deployment methods, and challenges, aiming to provide insights for developers and businesses. The survey anticipates growth in modern PHP versio

In this article, we're going to explore the notification system in the Laravel web framework. The notification system in Laravel allows you to send notifications to users over different channels. Today, we'll discuss how you can send notifications ov


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

SAP NetWeaver Server Adapter for Eclipse
Integrate Eclipse with SAP NetWeaver application server.

EditPlus Chinese cracked version
Small size, syntax highlighting, does not support code prompt function

Dreamweaver Mac version
Visual web development tools

Notepad++7.3.1
Easy-to-use and free code editor

VSCode Windows 64-bit Download
A free and powerful IDE editor launched by Microsoft
