4

I have quite big recursive array with mixed numeric and string keys.

Which is the fastest way to replace the numeric keys with string keys (prefix each numeric with item_)?

eg.

array('key_1' => 'val1', 2 => array( 3 => 'val3'));

to

array('key_1' => 'val1', 'item_2' => array('item_3' => 'val3'));

I want the order of the items remain the same.

asked Aug 24, 2010 at 19:11

1 Answer 1

5
function replace_numeric_keys(&$array) {
 $result = array();
 foreach ($array as $key => $value) {
 if (is_int($key)) $key = "item_$key";
 if (is_array($value)) $value = replace_numeric_keys($value);
 $result[$key] = $value;
 }
 return $result;
}
answered Aug 24, 2010 at 19:31

3 Comments

And the same using tail recursion would be?
@takeshin The recursive call is inside a loop.
I'm not sure you can use tail recursion since you're modifying the key and hence need to do something with the result of the recursive call (if it was only the value, it would be easy). Feel free to correct me if I'm wrong...

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.