Wednesday, July 3, 2024
HomeLanguagesPhpHow 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

Nicole Veronica Rubhabha
Nicole Veronica Rubhabha
A highly competent and organized individual DotNet developer with a track record of architecting and developing web client-server applications. Recognized as a personable, dedicated performer who demonstrates innovation, communication, and teamwork to ensure quality and timely project completion. Expertise in C#, ASP.Net, MVC, LINQ, EF 6, Web Services, SQL Server, MySql, Web development,
RELATED ARTICLES

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Most Popular

Recent Comments