0

Suppose I have an associative array:

    $array = array(
      "key1" => "value",
      "key2" => "value2");

And I wanted to make the keys all uppercase. How would I do than in a generalized way (meaning I could apply a user defined function to apply to the key names)?

RedBullet
  • 501
  • 6
  • 18

4 Answers4

5

You can use the array_change_key_case function of php

<?php
$input_array = array("FirSt" => 1, "SecOnd" => 4);
print_r(array_change_key_case($input_array, CASE_UPPER));
?>
Siddhartha Gupta
  • 1,140
  • 8
  • 13
  • Ah didn't know about that specific one, but the question was really more about a generalized mechanism like array_map where I could apply a user defined function to the keys. – RedBullet Jul 26 '13 at 01:25
  • Well with array_map you can't modulate keys as per your requirement. As more detailed explanation can be found here http://stackoverflow.com/a/3432266/2266525 – Siddhartha Gupta Jul 26 '13 at 05:49
3

Amazingly, there's an array_change_key_case function.

André Dion
  • 21,269
  • 7
  • 56
  • 60
1

Apart from the above answers -- the following code also does the trick. The benefit is you can use this for any operation on the keys than only making the keys uppercase.

<?php
   $arr = array(
      "key1" => "value",
      "key2" => "value2"
   );

  echo "<pre>";print_r($arr);echo "</pre>";

  $arra = array_combine(
        array_map(function($k){ 
           return strtoupper($k); 
        }, array_keys($arr)
    ), $arr);

  echo "<pre>";print_r($arra);echo "</pre>";

This code outputs as:

Array
(
    [key1] => value
    [key2] => value2
)
Array
(
    [KEY1] => value
    [KEY2] => value2
)

So this is just an alternative and more generic solution to change keys of an array.

Thanks.

Himel Nag Rana
  • 744
  • 1
  • 11
  • 19
0

You can use a foreach loop:

$newArray = array();
foreach ($array as $k => $v) {
    $newArray[strtoupper($k)] = $v;
}
jh314
  • 27,144
  • 16
  • 62
  • 82
  • 1
    This way, the old key still exists in the array. So, you also have to unset the old one using unset($array[$k]); – Benz Jul 25 '13 at 17:30