FUDforum
Fast Uncompromising Discussions. FUDforum will get your users talking.

Home » Imported messages » comp.lang.php » Inserting into associative array
Show: Today's Messages :: Polls :: Message Navigator
Return to the default flat view Create a new topic Submit Reply
Re: Inserting into associative array [message #169905 is a reply to message #169903] Wed, 29 September 2010 21:07 Go to previous messageGo to previous message
Hamish Campbell is currently offline  Hamish Campbell
Messages: 15
Registered: September 2010
Karma:
Junior Member
On Sep 30, 8:31 am, Jonathan Stein <jst...@image.dk> wrote:
> Hi.
>
> Let's say I have an array like
>    array(
>      'fruit' => 'banana',
>      'color' => 'yellow'
>    )
>
> Now I want to insert
>    'shape' => 'round'
> between 'fruit' and 'color'. I would think that PHP had a simple
> solution for that, but I haven't found it... My solution is to loop
> through the original array and build a new one.
>
> Does anyone have a better solution?
>
>    Regards
>
>      Jonathan

<?php
function array_insert(&$arr, $data, $pos) {
$array = array_slice($arr, 0, $pos) + $data +
array_slice($arr, $pos);
}

$a = array('a' => 'apple', 'b' => 'banana', 'o' => 'orange');
array_insert($a, array('p' => 'pear'), 2);

print_r($a);
// OUTPUT:
// Array ( [a] => apple [b] => banana [p] => pear [o] => orange )
?>

Regards

Hamish
[Message index]
 
Read Message
Read Message
Read Message
Read Message
Read Message
Read Message
Read Message
Previous Topic: PHP 5.3.3 Crashes on Win7
Next Topic: Dot in array key name
Goto Forum:
  

-=] Back to Top [=-
[ Syndicate this forum (XML) ] [ RSS ]

Current Time: Sun Nov 24 07:24:12 GMT 2024

Total time taken to generate the page: 0.38609 seconds