In PHP development, we often deal with key name case issues in arrays and the operation of extracting intersection keys from multiple arrays. array_change_key_case() and array_intersect_key() are two very practical array functions. When we use them together, we can achieve more flexible data filtering and comparison.
This article will explain how to effectively use array_change_key_case() with array_intersect_key() and use a practical example to illustrate its usage.
array_change_key_case() is used to convert all key names of an array to uppercase or lowercase.
grammar:
array_change_key_case(array $array, int $case = CASE_LOWER): array
The parameter $case is optional, and the default is CASE_LOWER (lower case), or can be set to CASE_UPPER (upper case).
array_intersect_key() is used to compare the key names of two (or more) arrays and return values whose key names are present in the first array.
grammar:
array_intersect_key(array $array1, array ...$arrays): array
Suppose we have two arrays, one is the form data submitted by the user and the other is the list of fields we allow to process. We want to extract the fields we are interested in from the form data and ignore the case differences.
<?php
// User-submitted data,Possible key names are inconsistent in case
$formData = [
'Name' => 'Alice',
'EMAIL' => 'alice@m66.net',
'Age' => 30,
'Location' => 'Beijing'
];
// Allowed fields(Unified in lowercase)
$allowedFields = [
'name' => true,
'email' => true
];
// Convert user data key names to lowercase
$normalizedFormData = array_change_key_case($formData, CASE_LOWER);
// Get the field of intersection key
$filteredData = array_intersect_key($normalizedFormData, $allowedFields);
// Output result
print_r($filteredData);
?>
Array
(
[name] => Alice
[email] => alice@vv99.net
)
This combination is useful when handling API requests, form validation, or user input cleaning. For example, when building a RESTful interface, we often want the field name to be case-insensitive and only accept fields that we explicitly allow.
By first using array_change_key_case() to unify the case of key names, and then using array_intersect_key() to filter out the required fields, we can perform more accurate and fault-tolerant processing of array data. This combination is simple in logic and has strong practicality, and is a very recommended model in PHP development.
If you are having trouble dealing with field matching or data cleaning, try this combination, which may make your code more concise and robust.