Reply to Re: how to replace an array key and keep the position?

Your name:

Reply:


Posted by Ian Hobson on 10/04/07 22:22

Marc Bauer wrote:
> Hi
>
> i'd like to replace an array key, but i cannot figure out how this could
> work.
>
> As an example this array:
>
> $array1 = array('key1' => 'value1', 'key2' => 'value2', 'key3' =>
> 'value3' );
>
> Now, i'd like to replace the 'key2' => 'value2' with 'key4' => 'value4' and
> the array should look like:
>
> $array1 = array('key1' => 'value1', 'key4' => 'value4', 'key3' =>
> 'value3' );
>
> The order of the keys is important... so i must replace on the same array
> position.
>
> Regards
> Marc
>
>
IIRC the order of the keys is NOT defined, except that integer keys
appear in increasing order. If this is right, your approach relies on
implementation details that may change. With that warning....

$array2 = Array();
foreach ($array1 as key -> value) {
if ($key == 'key2') {
$array2['key4'] = 'value4':
} else {
$array2[key] = $value;
}
}
$array1 = $array2;

Regards

Ian

[Back to original message]


Удаленная работа для программистов  •  Как заработать на Google AdSense  •  England, UK  •  статьи на английском  •  PHP MySQL CMS Apache Oscommerce  •  Online Business Knowledge Base  •  DVD MP3 AVI MP4 players codecs conversion help
Home  •  Search  •  Site Map  •  Set as Homepage  •  Add to Favourites

Copyright © 2005-2006 Powered by Custom PHP Programming

Сайт изготовлен в Студии Валентина Петручека
изготовление и поддержка веб-сайтов, разработка программного обеспечения, поисковая оптимизация