[nycphp-talk] Rename an array key?
Rob Marscher
rmarscher at beaffinitive.com
Tue Jul 24 14:01:06 EDT 2007
On Jul 24, 2007, at 1:29 PM, csnyder wrote:
> Oh well. I think I'll have to create a map and use that to keep the
> array in order:
>
> $set = array( 'vegetable'=>'tomato', 'fruit'=>'tomato',
> 'bean'=>'chickpea', 'grain'=>'corn' );
> $map = array_keys( $set );
> $map['bean'] = 'legume';
> $set['legume'] = $set['bean'];
> unset( $set['bean'] );
> foreach ( $map AS $orig_key=>$key ) {
> print $set[ $key ]."<br>";
> }
I don't think the -- $map['bean'] = 'legume'; -- part is doing what
you expect. It would have to be $map[2] = 'legume' intead.
Are you using php5? There's an array_combine() function... you could
do this:
$array = array('vegetable'=>'tomato', 'fruit'=>'tomato',
'bean'=>'chickpea', 'grain'=>'corn');
$keys = array_keys($array);
$values = array_values($array);
$keys[2] = 'legume';
$array = array_combine($keys, $values);
print_r($array);
That avoids a foreach loop. I am a little surprised php doesn't seem
to provide a function for swapping a key name in place.
More information about the talk
mailing list