Home > Backend Development > PHP Tutorial > PHP: How to filter array by specific key value range and keep key names?

PHP: How to filter array by specific key value range and keep key names?

王林
Release: 2024-05-01 21:39:02
Original
420 people have browsed it

How to filter a PHP array by a specific key value range and keep the key names? Follow these steps: Define a callback function that checks whether the key value is within the specified range. Call array_filter(), passing in the callback function and array as parameters.

PHP: How to filter array by specific key value range and keep key names?

PHP: How to filter an array by a specific key value range and keep the key names?

In PHP, we can use the array_filter() function to filter an array by a specific key value range while keeping the key names. This function accepts as argument a callback function that decides whether to retain each element in the array.

Callback function

The callback function should accept two parameters: key and value. It returns a Boolean value indicating whether the element should be retained.

Syntax

array_filter($array, $callback, $flag = 0);
Copy after login

Where:

  • $array is the array to be filtered.
  • $callback is a callback function that determines whether to retain each element in the array.
  • $flag is an optional parameter that specifies how to index the elements in the array.

Example

Suppose we want to filter out elements with key values ​​within a specific range from an associative array. Here are the steps to achieve this:

  1. Define a callback function that checks whether the key value is within the specified range.
  2. Call array_filter(), passing the callback function and array as parameters.

Code

<?php

$array = [
    "a" => 1,
    "b" => 2,
    "c" => 3,
    "d" => 4,
    "e" => 5,
];

// 定义回调函数
$callback = function ($key, $value) {
    return $value >= 2 && $value <= 4;
};

// 按键值范围过滤数组
$filteredArray = array_filter($array, $callback);

// 输出结果
print_r($filteredArray);
?>
Copy after login

Output

Array
(
    [b] => 2
    [c] => 3
    [d] => 4
)
Copy after login

As you can see, the resulting array only contains the key value 2 to 4, and the key names are preserved.

The above is the detailed content of PHP: How to filter array by specific key value range and keep key names?. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template