In PHP, array_change_key_case() is a function that changes the case of all key names in an array. It accepts two parameters:
array_change_key_case(array $array, int $case = CASE_LOWER): array
$array : the array to be processed;
$case : Optional parameter to specify the case of key name conversion ( CASE_LOWER or CASE_UPPER , default is lowercase).
Then the question is: what happens if the incoming is null or an empty array? Will the function report an error?
$result = array_change_key_case([]);
var_dump($result);
Output:
array(0) {
}
It can be seen that when an empty array is passed in, array_change_key_case() will execute normally and return an empty array . There will be no errors.
$data = null;
$result = array_change_key_case($data);
var_dump($result);
Output:
Warning: array_change_key_case(): Argument #1 ($array) must be of type array, null given
This code will trigger a warning that array_change_key_case() requires that the first parameter must be of array type. Passing in null will cause a warning and the function will not return a valid result (return null ).
If you are not sure whether the variable is an array, it is recommended to add a type check before calling the function:
$data = get_data_from_api('https://m66.net/api/data');
if (is_array($data)) {
$result = array_change_key_case($data, CASE_UPPER);
} else {
$result = [];
}
var_dump($result);
Doing this will prevent warnings when passing in null or other non-array types.
Pass in value | Is it reported an error | Return result |
---|---|---|
Empty array [] | no | Empty array [] |
null | yes | Issue a warning, return null |
array_change_key_case() is a practical array handler, but it requires that the parameters must be of array type. If you are writing more robust code, it is recommended to verify the data type first to prevent accidents.