Wednesday, February 23, 2011

php array change $key name?

Is there a function im not seeing that will change a specific array key's name?

Somethings like...

change_key($orig_name,$new_name);

...or am i going to have to loop through the array and create a new array from the old?
 
You could try something like this:
PHP Code:

function array_change_key_name$orig$new, &$array )
{
    if ( isset( 
$array[$orig] ) )
    {
        
$array[$new] = $array[$orig];
        unset( 
$array[$orig] );
    }
    return 
$array;
}
?>
But that will shift the new key to the end of the array. If you want to maintain the current position, then you'll probably have to loop, creating a new array with the old array's keys and then returning the new array:

function array_change_key_name$orig$new, &$array )
{
    foreach ( 
$array as $k => $v )
        
$return[ ( $k === $orig ) ? $new $k ] = $v;
    return ( array ) 
$return;
}
?>
You could easily make the second example recursive for multi-dimensional arrays, but they leave open the possibility of non-unique array keys... so if you'd like to change all matching keys in an array of any depth, you could try this... having to loop, creating a new array with the old array's keys and then returning the new array:
PHP Code:

function array_change_key_name$orig$new, &$array )
{
    foreach ( 
$array as $k => $v )
        
$return$k === $orig $new $k ] = ( is_array$v ) ? array_change_key_name$orig$new$v ) : $v );
    return 
$return;
}
?>
Just tested them all... you should be able to accomplish what you'd like. You could also switch the === for == if types make no difference.

Usage for all three exampels:
PHP Code:
$new_array array_change_key_name'old''new'$orig_array ); 
 

No comments:

Post a Comment