Jump to content


change key (name) in associative array?

  • Please log in to reply
2 replies to this topic

#1 Jim from Oakland

Jim from Oakland
  • Members
  • PipPipPip
  • Advanced Member
  • 41 posts

Posted 06 July 2006 - 01:36 AM

In the array (shown below) I need to change the 'name'
of one of the (first level) keys.

In the example, I'd like to change the key 'Boat' to
'Ship' without changing the order of the array

['Car']['Note']='needs work';
['Boat']['Note']='for sale';

Thanks a billion!

#2 toplay

  • Staff Alumni
  • Advanced Member
  • 973 posts

Posted 06 July 2006 - 02:05 AM

For all intensive purposes, an associative array doesn't have an order. That's why it's referenced by the "key" of the array.

You can do the following:

$ary['Car']['ID'] = '445';
$ary['Car']['Color'] = 'blue';
$ary['Car']['Note'] = 'needs work';
$ary['Boat']['ID'] = '491';
$ary['Boat']['Color'] = 'green';
$ary['Boat']['Note'] = 'for sale';
$ary['Plane']['ID'] = '420';
$ary['Plane']['Color'] = 'azure';
$ary['Plane']['Note'] = 'ready';

$ary['Ship']['ID'] = $ary['Boat']['ID'];
$ary['Ship']['Color'] = $ary['Boat']['Color'];
$ary['Ship']['Note'] = $ary['Boat']['Note'];


echo '<pre>', print_r($ary, TRUE), '</pre>';


However, the array will look like this:

    [Car] => Array
            [ID] => 445
            [Color] => blue
            [Note] => needs work

    [Plane] => Array
            [ID] => 420
            [Color] => azure
            [Note] => ready

    [Ship] => Array
            [ID] => 491
            [Color] => green
            [Note] => for sale


Which IMO is not wrong, since one can still access it using the 'Ship' key.

You might want to rethink what you're trying to do or how you're accessing the associative array.

#3 .josh

  • Staff Alumni
  • .josh
  • 14,871 posts

Posted 06 July 2006 - 04:53 AM

just out of curiosity..why do you wanna do this? at face value, all i can suggest (other than toplay's suggestion) is..why not just change it in the code to ship, if you want to use ship instead of boat?
Did I help you? Feeling generous? Buy me lunch! 
Please, take the time and do some research and find out how much it would have cost you to get your help from a decent paid-for source. A "roll-of-the-dice" freelancer will charge you $5-$15/hr. A decent entry level freelancer will charge you around $15-30/hr. A professional will charge you anywhere from $50-$100/hr. An agency will charge anywhere from $100-$250/hr. Think about all this when soliciting for help here. Think about how much money you are making from the work you are asking for help on. No, we do not expect you to pay for the help given here, but donating a few bucks is a fraction of the cost of what you would have paid, shows your appreciation, helps motivate people to keep offering help without the pricetag, and helps make this a higher quality free-help community :)

0 user(s) are reading this topic

0 members, 0 guests, 0 anonymous users