changing key names

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
User avatar
Korvus
Forum Newbie
Posts: 4
Joined: Mon Jul 05, 2004 1:15 am
Location: Lleida ( Spain )

changing key names

Post by Korvus »

hi all!

is there any way of changing an array key name without loosing its internal pointer position?

i've found some functions at php.net but they aren't useful on my case
thx in advance
User avatar
Weirdan
Moderator
Posts: 5978
Joined: Mon Nov 03, 2003 6:13 pm
Location: Odessa, Ukraine

Post by Weirdan »

hm...
something like this perhaps:

Code: Select all

function rename_key($array, $from, $to) {
    $keys = array_keys($array);
    $vals = array_values($array);
    $ret = array();
    for($i = 0, $len = count($keys); $i<$len; $i++) {
        if($keys[$i] == $from) $keys[$i] = $to;
        $ret[ $keys[$i] ] = $vals[$i];
    }
    return $ret;
}
Post Reply