Jump to: navigation, search

Php array change key case

From w3cyberlearnings

Contents

PHP function array_change_key_case

This function changes all keys in an array to upper case or lower case.

Syntax array_change_key_case

  • array: array
  • case: CASE_LOWER (for lower case), CASE_UPPER (for upper case)
array_change_key_case(array, case);

Note

  • This function accept the array as an associative array. If you use the normal array, you need to modify the array and turn it to associative array.

Example 1: change array key to upper case

<?php

$city = array('usa' => 'New York',
	 'cambodia' => 'Phnom Penh',
	 'thailand' => 'Bangkor',
	 'china' => 'Hong Kong',
	 'new zealand' => 'Auckland');
print_r(array_change_key_case($city, CASE_UPPER));
?>

Output

Array
(
    [USA] => New York
    [CAMBODIA] => Phnom Penh
    [THAILAND] => Bangkor
    [CHINA] => Hong Kong
    [NEW ZEALAND] => Auckland
)

Example 2: change array key to lower case

<?php

$city = array('USA' => 'New York',
	 'CAMBODIA' => 'Phnom Penh',
	 'THAILAND' => 'Bangkor',
	 'CHINA' => 'Hong Kong',
	 'NEW ZEALAND' => 'Auckland');
$city = array_change_key_case($city, CASE_LOWER);
print_r($city);
?>

Output

Array
(
    [usa] => New York
    [cambodia] => Phnom Penh
    [thailand] => Bangkor
    [china] => Hong Kong
    [new zealand] => Auckland
)

Example 3: change the normal array to lower case

  • You need to use array_flip() function to flip the array before you can use

array_change_key_case. After the final result, you can flip it back.

<?php

$city = array('New York',
	 'Phnom Penh',
	 'Bangkor',
	 'Hong Kong',
	 'Auckland');
$city = array_flip($city);
$city = array_change_key_case($city, CASE_LOWER);
print_r($city);
?>

Output

Array
(
    [new york] => 0
    [phnom penh] => 1
    [bangkor] => 2
    [hong kong] => 3
    [auckland] => 4
)

Related Links


Navigation
Web
SQL
MISC
References