In daily PHP development, we often need to filter arrays based on certain "whitelist keys" or "blacklist keys". The array_flip() and array_intersect_key() functions provided by PHP can achieve this requirement very efficiently. This article will use specific code examples to introduce how to use these two functions to complete the task of array filtering.
This function is used to swap keys and values in an array.
array_flip(array $array): array
Input: an array.
Output: The array after the key value pair is flipped (note: the value of the original array must be unique and can be used as a scalar value for the key).
This function is used to return elements in the array where all keys also exist in another array.
array_intersect_key(array $array, array ...$arrays): array
Input: Two or more arrays.
Output: Only elements in the first array that appear in all subsequent arrays at the same time.
Suppose we receive the following data from the user form:
$userInput = [
'username' => 'john_doe',
'password' => '123456',
'email' => 'john@example.com',
'token' => 'abcd1234', // Illegal fields
];
We only want to keep the three fields 'username' , 'password' and 'email' , and the others should be filtered out.
$allowedKeys = ['username', 'password', 'email'];
// Change allowed keys to key names
$allowedKeysFlipped = array_flip($allowedKeys);
// Get the intersection,Keep fields with the same key
$filteredInput = array_intersect_key($userInput, $allowedKeysFlipped);
print_r($filteredInput);
Array
(
[username] => john_doe
[password] => 123456
[email] => john@example.com
)
In this way, we can filter arrays flexibly and securely, avoiding illegal fields being continued to be processed or even written to the database.
Suppose you have developed an API interface and receive the following URL parameters:
https://m66.net/api/user/update?username=jane&password=78910&is_admin=1
You do not want the client to modify sensitive fields such as is_admin at will, and only update username and password .
You can do this:
$input = $_GET;
$allowed = ['username', 'password'];
$safeInput = array_intersect_key($input, array_flip($allowed));
// Now $safeInput Contains only allowed fields
This method can easily implement the whitelisting mechanism of API parameters and enhance security.
By combining array_flip() and array_intersect_key() , we can implement key filtering operations of arrays very conveniently. This approach is not only concise in code and high performance, but also easy to maintain. It is suitable for form processing, API parameter filtering and other scenarios.
In actual development, it is recommended to encapsulate this logic into a function, for example:
function filter_array_keys(array $data, array $allowedKeys): array {
return array_intersect_key($data, array_flip($allowedKeys));
}
This way, your code will be more modular and readable.