Jump to content

change key (name) in associative array?


Recommended Posts

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
entries.

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

Thanks a billion!
Link to comment
https://forums.phpfreaks.com/topic/13804-change-key-name-in-associative-array/
Share on other sites

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:
[code]
<?php

$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'];

unset($ary['Boat']['ID']);
unset($ary['Boat']['Color']);
unset($ary['Boat']['Note']);
unset($ary['Boat']);

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

?>
[/code]

However, the array will look like this:
[quote]
Array
(
    [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
        )

)
[/quote]

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.

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.