• PHP Video Tutorials

PHP array_change_key_case() Function



Definition and Usage

The array_change_key_case() function changes the case of all keys of the passed array and returns an array with all keys either in lower case or upper case based on the option passed.

By default this function returns lower cased keys.

Syntax

array array_change_key_case ( array $input [, int $case] )

Parameters

Sr.No Parameter & Description
1

input (Mandatory)

This is the array for which you want to change the case of all the keys.

2

case (Optional)

This will take constant value either CASE_UPPER or CASE_LOWER. If you do not pass this value then function will change the keys to lower case.

Return Values

PHP array_change_key_case() function returns an array with its keys either in lower case or upper case, or FALSE if passed input is not a valid PHP array.

PHP Version

This function was first introduced in PHP Version 4.2.0.

Example

Try out following example in which we are converting all the keys into upper case −

<?php
   $input = array("FirSt"=> 10, "SecOnd" => 400, "Third" => 800, );
   print_r(array_change_key_case($input, CASE_UPPER));
?>

This will produce following result −

Array
(
    [FIRST] => 10
    [SECOND] => 400
    [THIRD] => 800
)

Example

Following example converts all the keys into lower case −

<?php
   $input = array("FirSt"=> 10, "SecOnd" => 400, "Third" => 800, );
   print_r(array_change_key_case($input, CASE_LOWER));
?>

This will produce following result −

Array
(
    [first] => 10
    [second] => 400
    [third] => 800
)

Example

Let's check how default case will work if we don't pass second option in the function −

<?php
   $input = array("FirSt"=> 10, "SecOnd" => 400, "Third" => 800, );
   print_r(array_change_key_case($input));
?>

This will produce following result −

Array
(
    [first] => 10
    [second] => 400
    [third] => 800
)

Example

Following example returns FALSE and raises a warning because we are trying to pass a simple PHP string instead of a PHP array −

<?php
   $input = "This is a string";
   print_r(array_change_key_case($input, CASE_LOWER));
?>

This does not produce any output, rather it will display following warning, and if you will check function return value then it will be FALSE −

PHP Warning: array_change_key_case() expects parameter 1 to be array, string given in main.php on line 3
php_function_reference.htm
Advertisements