Tuesday, September 24, 2024
Google search engine
HomeLanguagesHow to Change Array Key to Lowercase in PHP ?

How to Change Array Key to Lowercase in PHP ?

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
  
// PHP Program to change the key 
// case to lovercase
function change_case($arr) {
    return array_change_key_case($arr, CASE_LOWER);
}
  
// Driver Code
$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
  
// PHP Program to change the key
// case to lovercase
function change_case($arr)
{
    foreach ($arr as $key => $val) {
        echo strtolower($key
            . " => " . $val . "\n";
    }
}
  
// Driver Code
$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

RELATED ARTICLES

Most Popular

Recent Comments