[nycphp-talk] Rename an array key?
Jon Baer
jonbaer at jonbaer.com
Tue Jul 24 14:14:05 EDT 2007
All that is really needed is a preserve_key to be added to
array_splice function and you pretty much have it ...
- Jon
On Jul 24, 2007, at 2:01 PM, Rob Marscher wrote:
> 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.
>
> _______________________________________________
> New York PHP Community Talk Mailing List
> http://lists.nyphp.org/mailman/listinfo/talk
>
> NYPHPCon 2006 Presentations Online
> http://www.nyphpcon.com
>
> Show Your Participation in New York PHP
> http://www.nyphp.org/show_participation.php
More information about the talk
mailing list