Current Location: Home> Latest Articles> Discussion on the order of array_slice and array_filter

Discussion on the order of array_slice and array_filter

gitbox 2025-05-20

In PHP, array_slice() and array_filter() are two commonly used array processing functions. One is used to intercept part of an array, and the other is used to filter elements in the array that match the criteria. When we are processing data, we often need to use these two functions together. But have you thought about it:

The answer is: Yes, the order will affect the results , and in some scenarios the impact is very large.

A brief review of the function introduction

  • array_filter(array $array, callable|null $callback = null): array
    Returns the array filtered by the callback function. If the callback function is not passed, PHP will automatically remove all elements with a value of false (including 0 , '' , null , false , etc.).

  • array_slice(array $array, int $offset, ?int $length = null, bool $preserve_keys = false): array
    Returns an array of sub-arrays in the array. Supports negative offsets, and you can choose whether to retain the original key.

Example Analysis

Suppose we have the following array:

 $data = [0, 1, 2, 3, 4, 5];

We need to do the following:

  1. Filter out elements with values ​​greater than 2;

  2. Take the first two elements from the filtered result.

Array_filter and then array_slice

 $filtered = array_filter($data, function($item) {
    return $item > 2;
});
$result = array_slice($filtered, 0, 2);
print_r($result);

Output:

 Array
(
    [3] => 3
    [4] => 4
)

Note that the output here is to filter out elements greater than 2 (i.e. 3, 4, 5) from the original array, and then take the first two. If you do not set preserve_keys to true , array_slice will be reindexed (the default behavior of setting it to false ) and the output will become:

 $result = array_slice(array_values($filtered), 0, 2);

Output:

 Array
(
    [0] => 3
    [1] => 4
)

Array_slice first and array_filter

 $sliced = array_slice($data, 0, 4);
$result = array_filter($sliced, function($item) {
    return $item > 2;
});
print_r($result);

Output:

 Array
(
    [3] => 3
)

Here we take the first 4 elements (0, 1, 2, 3), and then filter out the items greater than 2, and there is only one result: 3 .

Which order is more appropriate?

  • If you want to take the first few results from all elements that meet the criteria : array_filter first, then array_slice .

  • If you want to filter items that meet the criteria from the first few items in the original array : array_slice first, then array_filter .

This is especially critical when paging, data flow optimization, and processing large datasets.

Examples of applications in real scenarios

Suppose you have an API interface https://gitbox.net/api/posts , which returns an array of posts. You want to filter out the top 5 posts with the keyword "PHP" in the title:

 $response = file_get_contents('https://gitbox.net/api/posts');
$posts = json_decode($response, true);

$filtered = array_filter($posts, function($post) {
    return strpos($post['title'], 'PHP') !== false;
});

$topFive = array_slice(array_values($filtered), 0, 5);

print_r($topFive);

Writing this ensures that you get really "the top five of all posts containing PHP".

Conversely, if you want to filter only those containing "PHP" from the first 10 posts you return:

 $topTen = array_slice($posts, 0, 10);
$filtered = array_filter($topTen, function($post) {
    return strpos($post['title'], 'PHP') !== false;
});

print_r($filtered);

summary

  • Different orders, the results may be very different.

  • Filter first and then intercept, which is applicable to "preferred parts of all data";

  • Intercept first and then filter, which is suitable for "limiting the previous part of the data before filtering".

When using the combination of array_slice and array_filter , you must clarify the scope of your target data, so as to determine the order and avoid logical errors or unexpected results.