Current Location: Home> Latest Articles> Combining array_slice and array_map to process array fragments

Combining array_slice and array_map to process array fragments

gitbox 2025-05-26

During PHP development, we often need to process some elements in an array instead of traversing the entire array. To achieve this, array_slice and array_map are two very useful functions. This article will explain in detail how to use them in combination to enable efficient processing of a part of an array, and illustrate it with actual code examples.

1. Introduction to array_slice

array_slice is a function provided by PHP to extract a sub-array from an array without modifying the original array. The basic syntax is as follows:

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

  • $offset : The starting offset, which can be a negative number to indicate starting from the tail.

  • $length : The number of elements to be extracted, if omitted, it will be extracted to the end of the array.

  • $preserve_keys : Whether to preserve the key name of the original array.

2. Introduction to array_map

array_map is used to act on each element in the array and return the processed new array. The basic syntax is as follows:

 array_map(callable $callback, array $array): array

It will iterate through the entire array, pass each element as an argument to the callback function, and return the result as a new array.

3. Combined use scenarios and ideas

When processing large arrays, if we only care about part of the data (such as paging, conditional processing, etc.), we first use array_slice to extract the target part, and then use array_map to process it, which is not only clear in logic, but also has better performance.

4. Sample code

Suppose we have an array of products, each product is an associative array, we only need to process the names of the first 5 products and add a prefix uniformly:

 <?php

$products = [
    ['id' => 1, 'name' => 'computer'],
    ['id' => 2, 'name' => 'cell phone'],
    ['id' => 3, 'name' => 'earphone'],
    ['id' => 4, 'name' => 'mouse'],
    ['id' => 5, 'name' => 'keyboard'],
    ['id' => 6, 'name' => 'monitor'],
];

// Before taking it out 5 A product
$firstFive = array_slice($products, 0, 5);

// Prefix the name“recommend:”
$processed = array_map(function($product) {
    $product['name'] = 'recommend:' . $product['name'];
    return $product;
}, $firstFive);

// Output result
foreach ($processed as $item) {
    echo $item['id'] . ' - ' . $item['name'] . PHP_EOL;
}

The output result is:

 1 - recommend:computer
2 - recommend:cell phone
3 - recommend:earphone
4 - recommend:mouse
5 - recommend:keyboard

5. Combined with practical application scenarios

This method is particularly common in interface development, such as in an API interface that returns a user list:

 <?php

// Simulate to obtain user data(Can be from the database)
$users = [
    ['id' => 101, 'email' => '[email protected]'],
    ['id' => 102, 'email' => '[email protected]'],
    ['id' => 103, 'email' => '[email protected]'],
    ['id' => 104, 'email' => '[email protected]'],
    ['id' => 105, 'email' => '[email protected]'],
    ['id' => 106, 'email' => '[email protected]'],
];

// Assume that the paging parameters are displayed per page 3 strip,Currently the first 2 Page
$page = 2;
$pageSize = 3;
$offset = ($page - 1) * $pageSize;

// 分Page获取当前Page的数据
$pagedUsers = array_slice($users, $offset, $pageSize);

// Format email address in lowercase
$formatted = array_map(function($user) {
    $user['email'] = strtolower($user['email']);
    return $user;
}, $pagedUsers);

// JSON Output
header('Content-Type: application/json');
echo json_encode($formatted);

The return result will be:

 [
    {"id":104,"email":"[email protected]"},
    {"id":105,"email":"[email protected]"},
    {"id":106,"email":"[email protected]"}
]

6. Performance and readability

The main advantages of using array_slice and array_map are:

  • Avoid unnecessary calculations : only process the part of the data you need.

  • Logical separation : the steps of data filtering and data processing are clear and clear, and the code is highly readable.

  • Strong maintainability : convenient to expand logic in the future, such as modifying paging or processing logic.

Conclusion

When processing large amounts of data, using array_slice and array_map reasonably can not only improve performance, but also make the code more concise and easy to understand. Whether in the background management system, data interface, or in actual business logic, this model is worth learning from and applying.