AudiS2 Posted September 20, 2008 Share Posted September 20, 2008 Let say I have an example array('color'=>'green', 'size'=>'big') How can I insert 'weight'=>'heavy' at the beginning of array? array_unshift would not accept 'weight'=>'heavy' as a parametar. Quote Link to comment Share on other sites More sharing options...
papaface Posted September 20, 2008 Share Posted September 20, 2008 something like <?php $array1 = array('color'=>'green', 'size'=>'big'); $array2 = array("weight"=>"heavy"); $result = array_merge($array2, $array1); print_r($result); ?> Quote Link to comment Share on other sites More sharing options...
AudiS2 Posted September 20, 2008 Author Share Posted September 20, 2008 Sorry I see now that my actual question was how to insert value between 'color' and 'size' so that at the end I have array('color'=>'green', "weight"=>"heavy", 'size'=>'big') Quote Link to comment Share on other sites More sharing options...
papaface Posted September 20, 2008 Share Posted September 20, 2008 what difference does it make where it is located? Why do you require it in such a precise location within the array? Quote Link to comment Share on other sites More sharing options...
.josh Posted September 20, 2008 Share Posted September 20, 2008 One thing I can think of is it would mean the difference between having to manually echo out things in a specific order and just looping. Anyways, here's my take: <?php $array1 = array('color'=>'green', 'size'=>'big'); foreach ($array1 as $key => $val) { if ($key == 'size') { $newarray['weight'] = 'heavy'; } $newarray[$key] = $val; } print_r($newarray); ?> 'weight' => 'heavy' is hardcoded into the condition because I don't really know where that's coming from. You'll have to insert your own var there. Quote Link to comment Share on other sites More sharing options...
AudiS2 Posted September 20, 2008 Author Share Posted September 20, 2008 Thanks Crayon . Copying seems to be only way. There is no function in PHP that says insert an element to an array at that position. Quote Link to comment Share on other sites More sharing options...
.josh Posted September 20, 2008 Share Posted September 20, 2008 Nope, apparently not. Seems kind of odd that there doesn't seem to be a built-in array_insert function to insert a key=>value or even just value into a specific position of an array, like after or before a specified element. I figured out a bunch of alternate methods to achieve the same thing, using various other array manipulation functions, but overall, ^^ seemed to be the quickest and simplest method, imo. Quote Link to comment Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.