How to Change Array Key to Lowercase in PHP ?
Last Updated :
27 Sep, 2023
This article will show you how to change the array key case to lowercase using PHP. There are two approaches to changing the key case, these are:
- Using array_change_key_case() function
- Using foreach() and strtolower() functions
Approach 1: Using array_change_key_case() function
The array_change_key_case() function is used to change the case of all of the keys in a given array either to lower case or upper case. To change the key case to lowercase, we will add the value “CASE_LOWER”.
Syntax:
array_change_key_case($arr, CASE_LOWER)
Example 1:
PHP
<?php
function change_case( $arr ) {
return array_change_key_case ( $arr , CASE_LOWER);
}
$arr = [
"NAME" => "Akash" ,
"COMPANY" => "GFG" ,
"Address" => "Noida" ,
"Contact NO" => "+91-9876543210" ,
];
print_r(change_case( $arr ));
?>
|
Output
Array
(
[name] => Akash
[company] => GFG
[address] => Noida
[contact no] => +91-9876543210
)
Approach 2: Using foreach() and strtolower() functions
In this approach, we will use foreach() loop to select each key one by one, and then use strtolower() function to convert the key to lowercase.
Example:
PHP
<?php
function change_case( $arr )
{
foreach ( $arr as $key => $val ) {
echo strtolower ( $key )
. " => " . $val . "\n" ;
}
}
$arr = [
"NAME" => "Akash" ,
"COMPANY" => "GFG" ,
"Address" => "Noida" ,
"Contact NO" => "+91-9876543210" ,
];
print_r(change_case( $arr ));
?>
|
Output
name => Akash
company => GFG
address => Noida
contact no => +91-9876543210
Share your thoughts in the comments
Please Login to comment...