NYCPHP Meetup

NYPHP.org

[nycphp-talk] Rename an array key?

csnyder chsnyder at gmail.com
Tue Jul 24 13:29:57 EDT 2007


On 7/24/07, Ben Sgro (ProjectSkyLine) <ben at projectskyline.com> wrote:
> Great question...
> I just spent some time to figure it out and came up with a cool way!
>
> <?php
> $set = array( 'vegetable'=>'lettuce', 'fruit'=>'coconut',
> 'bean'=>'chickpea',
>        'grain'=>'corn' );
> $set = array_flip($set);
> $set['chickpea'] = 'legume';
> $set = array_flip($set);
>
> /*
> $set2 = array_slice($set, -2, 1);
> $set2 = array_flip($set2);
> $set['chickpea
> */
> print_r($set);

Good one! Er, except, it breaks if you have duplicate values in the array.

Try it with  $set = array( 'vegetable'=>'tomato', 'fruit'=>'tomato',
'bean'=>'chickpea', 'grain'=>'corn' );

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>";
}

As Tim Gales is fond of saying, "Any problem in computer science can
be solved with another layer of indirection."

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



More information about the talk mailing list