NYCPHP Meetup

NYPHP.org

[nycphp-talk] Rename an array key?

csnyder chsnyder at gmail.com
Tue Jul 24 15:52:08 EDT 2007


On 7/24/07, Rob Marscher <rmarscher at beaffinitive.com> 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.

Right, I keep forgetting that about array_keys()... I remember using
array_combine() for building just such a key=>key array before.

> $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.

Yeah, me too.

Thanks!

-- 
Chris Snyder
http://chxo.com/



More information about the talk mailing list