[nycphp-talk] Rename an array key?
csnyder
chsnyder at gmail.com
Tue Jul 24 16:15:18 EDT 2007
On 7/24/07, David Krings <ramons at gmx.net> wrote:
> 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.
Sometimes it matters because you want things to be in a particular
order. In this case, I have an array with a whole bunch of form values
for a unit test. I want to rename one of the keys, but I want the
values to be in the same order. Of course there are other ways to do
it, which is probably why no one has bothered to code
array_key_replace().
> 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.
True, and without jumping through as many hoops as my hack involving $map.
$keys = array_keys( $set );
$values = array_values( $set );
$replace = array_search( 'bean', $keys );
if ( $replace !== FALSE ) {
$keys[ $replace ] = 'legume';
}
$set = array_combine( $keys, $values );
Thanks, David.
--
Chris Snyder
http://chxo.com/
More information about the talk
mailing list