Looking for array_map equivalent to work on keys in associative arrays [duplicate]
Asked Answered
G

4

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)?

Gazetteer answered 25/7, 2013 at 17:23 Comment(0)
L
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));
?>
Lamee answered 25/7, 2013 at 17:28 Comment(2)
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.Gazetteer
Well with array_map you can't modulate keys as per your requirement. As more detailed explanation can be found here https://mcmap.net/q/86096/-difference-between-array_map-array_walk-and-array_filterLamee
P
3

Amazingly, there's an array_change_key_case function.

Possie answered 25/7, 2013 at 17:28 Comment(0)
L
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.

Lister answered 30/4, 2015 at 6:34 Comment(0)
K
0

You can use a foreach loop:

$newArray = array();
foreach ($array as $k => $v) {
    $newArray[strtoupper($k)] = $v;
}
Kaela answered 25/7, 2013 at 17:29 Comment(1)
This way, the old key still exists in the array. So, you also have to unset the old one using unset($array[$k]);Kizzykjersti

© 2022 - 2024 — McMap. All rights reserved.