js

Thursday, January 11, 2024

Explain array_change_key_case() function in php

The array_change_key_case function in PHP is used to change the case of all keys in an array. It returns a new array with the keys converted to lowercase or uppercase, depending on the specified case parameter.

Here's the basic syntax of the array_change_key_case function:

php
array_change_key_case(array $array, int $case = CASE_LOWER): array

Parameters:

  • $array: The input array whose keys will be changed.
  • $case: The case to which the keys will be converted. It can take one of two constants: CASE_LOWER (default) for converting keys to lowercase, or CASE_UPPER for converting keys to uppercase.

Let's look at a couple of examples to illustrate how array_change_key_case works:

Example 1: Converting Keys to Lowercase

php
$inputArray = array( 'FirstName' => 'John', 'LastName' => 'Doe', 'Age' => 30 ); $lowercaseKeys = array_change_key_case($inputArray, CASE_LOWER); print_r($lowercaseKeys);

Output:

php
Array ( [firstname] => John [lastname] => Doe [age] => 30 )

Example 2: Converting Keys to Uppercase

php
$inputArray = array( 'firstname' => 'John', 'lastname' => 'Doe', 'age' => 30 ); $uppercaseKeys = array_change_key_case($inputArray, CASE_UPPER); print_r($uppercaseKeys);

Output:

php
Array ( [FIRSTNAME] => John [LASTNAME] => Doe [AGE] => 30 )

In these examples, the function array_change_key_case takes an input array and returns a new array with all keys converted to either lowercase or uppercase, based on the specified case. The original input array remains unchanged. This function can be useful when you need to standardize the case of keys for consistency in array manipulation.

 

No comments:

Post a Comment