NYCPHP Meetup

NYPHP.org

[nycphp-talk] Rename an array key?

David Krings ramons at gmx.net
Tue Jul 24 16:01:52 EDT 2007


csnyder wrote:
> On 7/24/07, Jon Baer <jonbaer at jonbaer.com> wrote:
>> All that is really needed is a preserve_key to be added to
>> array_splice function and you pretty much have it ...
>>
>> - Jon
> 
> Indeed. When I saw your post I got all excited about doing something like:
> 
> array_splice( $set, 3, 1, array('legume'=>'chickpea') );
> 
> But as you point out, "keys in replacement array are not preserved."
> Not really worthy of the name "splice" in my opinion.

I looked at that splice function a bit more and at arrays as well. I 
still don't get why the position matters. To me the key of an array is 
like the autoincrement primary key on a table. You can't just start 
messing around with it and expect everything to be fine.

What you could do is split the array into two numerically keyed arrays. 
Each array can then be referenced using the same key and you can then 
change the value of the desired original key in the array with the 
original keys. Once done you glue the two together by specifying the key 
for the glued array.
That preserves keys (except for the one you changed, of course) as well 
as order and can handle duplicates if there would be any.

David



More information about the talk mailing list