NYCPHP Meetup

NYPHP.org

[nycphp-talk] Rename an array key?

David Krings ramons at gmx.net
Tue Jul 24 12:03:24 EDT 2007


csnyder wrote:
> Anyone know of an easy way to rename an associative array key in place?
> 
> array( 'vegetable'=>'lettuce', 'fruit'=>'coconut', 'bean'=>'chickpea',
> 'grain'=>'corn' )
> 
> I want the third element to be 'legume'=>'chickpea', but it seems to
> involve rebuilding the array...?
> 
What you can do is first identify the key/value pair you want to change. 
Then read out the value, then use unset($array['key']), then add the 
saved value to the array with the desired key name.

Is there an easier way? Maybe...I'd just open the main page for the 
array functions in the PHP documentation and go down the list if there 
is anything that can do that in one line of code. I have it open and 
browsed through the list and the only somewhat likely candidate is 
array_splice...but I cannot figure anything out with these hypothetical 
examples that the PHP documentation always has.

My first proposal will for sure work.

David



More information about the talk mailing list