Current Location: Home> Latest Articles> How to use array_slice to extract part of an array

How to use array_slice to extract part of an array

gitbox 2025-05-26

In PHP programming, when processing arrays, we often need to extract a certain part of the data in the array. Manual loop traversal is not only cumbersome, but also prone to errors. Fortunately, PHP has a very practical function built in - array_slice , which can easily implement this function.

What is array_slice?

The array_slice function can extract a sub-array of a specified length from an array without changing the structure of the original array. Its function prototype is as follows:

 array array_slice(array $array, int $offset, ?int $length = null, bool $preserve_keys = false)
  • $array : The original array to operate.

  • $offset : The starting position of the extract (starting from 0, negative numbers are supported, and negative numbers are calculated from the end of the array).

  • $length : The length of the extract, if omitted, it will be extracted to the end of the array by default.

  • $preserve_keys : Whether to retain the key name of the original array, default to false , that is, re-index.

Example of usage

Suppose we have an array containing numbers:

 $numbers = [10, 20, 30, 40, 50, 60];

Example 1: Extract 3 consecutive elements starting from the second element

 $slice = array_slice($numbers, 1, 3);
print_r($slice);

Output result:

 Array
(
    [0] => 20
    [1] => 30
    [2] => 40
)

Note that although the index of the original array starts at 1, the index of the output array starts at 0.

Example 2: Extract 2 elements from the end of the array

 $slice = array_slice($numbers, -2, 2);
print_r($slice);

Output result:

 Array
(
    [0] => 50
    [1] => 60
)

Example 3: Keep the original array key name

 $slice = array_slice($numbers, 2, 2, true);
print_r($slice);

Output result:

 Array
(
    [2] => 30
    [3] => 40
)

At this time, the key name in the original array is retained.

Combined with actual scenarios: pagination effect

Suppose you have an array representing all records in the database. If you want to implement paging, display 5 pieces of data per page, you can write it like this:

 $allData = range(1, 100); // simulation 1-100 Data of
$page = 3; // Current page number
$perPage = 5; // Number of data per page
$offset = ($page - 1) * $perPage;

$pageData = array_slice($allData, $offset, $perPage);
print_r($pageData);

Output as page 3 data:

 Array
(
    [0] => 11
    [1] => 12
    [2] => 13
    [3] => 14
    [4] => 15
)

Things to note

  • If $offset exceeds the array length, array_slice returns an empty array.

  • When $length is negative, the corresponding number of elements will be excluded from the end of the array.

  • When slicing the associative array, it is recommended to enable the $preserve_keys parameter, otherwise it will be re-indexed, which may affect subsequent logic.

Summarize

array_slice is a powerful tool for handling array cutting in PHP. It is simple and efficient, especially suitable for common needs such as paging and data interception. Mastering its parameters can make your array processing more flexible and accurate.


 // Sample code demonstration array_slice Basic usage
$fruits = ['apple', 'banana', 'orange', 'pear', 'grape'];

// Starting from the second element3Elements
$sliced = array_slice($fruits, 1, 3);
print_r($sliced);
 // Combined URL Example,Assume that it is to be replaced URL The domain name is gitbox.net
$url = "https://example.com/path/to/resource";
$modifiedUrl = preg_replace('/https?:\/\/[^\/]+/', 'https://gitbox.net', $url);
echo $modifiedUrl; // Output https://gitbox.net/path/to/resource

In this way, replacing domain names is also very simple and practical in PHP code involving URL processing.