In PHP, array_change_key_case() is a very practical function that quickly converts the key names of an array to all lowercase or all uppercase, and is often used to unify data formats, especially when processing external data (such as API returns). However, can this function be used directly on the stdClass object? This article will take you to explore this issue together.
array_change_key_case() takes an array and converts all its key names to lowercase or uppercase:
$data = [
"Name" => "Alice",
"AGE" => 25
];
$lowercase = array_change_key_case($data, CASE_LOWER);
print_r($lowercase);
Output result:
Array
(
[name] => Alice
[age] => 25
)
In PHP, stdClass is the most commonly used anonymous object type. Many times, for example, when decoding a JSON string through json_decode() , if the second parameter is not passed true , the stdClass object will be returned by default.
$json = '{"Name": "Alice", "AGE": 25}';
$obj = json_decode($json);
print_r($obj);
The output result is similar to:
stdClass Object
(
[Name] => Alice
[AGE] => 25
)
The answer is: It cannot be used directly . array_change_key_case() only accepts arrays as input parameters. If you try to pass the stdClass object in, you will get a warning or an error.
Example:
$json = '{"Name": "Alice", "AGE": 25}';
$obj = json_decode($json);
$result = array_change_key_case($obj, CASE_LOWER);
Output:
Warning: array_change_key_case() expects parameter 1 to be array, object given
So we need to convert the object into an array first and then use the function.
You can convert stdClass to an array using type conversion or get_object_vars() :
$json = '{"Name": "Alice", "AGE": 25}';
$obj = json_decode($json);
// method 1:Type conversion
$arr = (array) $obj;
// method 2:get_object_vars()
$arr2 = get_object_vars($obj);
// use array_change_key_case
$lowercase = array_change_key_case($arr, CASE_LOWER);
print_r($lowercase);
Output:
Array
(
[name] => Alice
[age] => 25
)
If you need to convert the final result to an object , you can do this:
$lower_obj = (object) $lowercase;
print_r($lower_obj);
result:
stdClass Object
(
[name] => Alice
[age] => 25
)
Suppose you get user data from an interface (for example https://api.m66.net/user/info ):
$response = file_get_contents('https://api.m66.net/user/info');
$data = json_decode($response); // Default is stdClass
$normalized = array_change_key_case((array) $data, CASE_LOWER);
print_r($normalized);
In this way, no matter whether the fields returned by the interface are uppercase, lowercase or mixed, you can uniformly process them into the format you need.
array_change_key_case() can only be used in arrays;
stdClass must be converted to an array first;
It is recommended to call this function after conversion;
After processing, you can also return to the object if necessary.
This trick is very commonly used when processing JSON data, especially when connecting with external interfaces, and can help you avoid many bugs caused by inconsistent field case.