1

Possible Duplicate:
PHP - add item to beginning of associative array

have associative array:

$myarray=array("key1"=>"value1","key2"=>"value2");

Need to add a new element to array:

$myarray["keynew"]="valuenew";

So now $myarray is:

Array ( [key1] => value1 [key2] => value2 [keynew] => valuenew ) 

How can I move the new added element ("keynew"=>"valuenew") to the first position of the array?

I have an workaround, but I don't like it.

$myarray=array("key1"=>"value1","key2"=>"value2");
$myarray["keynew"]="-valuenew";
asort($myarray);
$myarray["keynew"]="valuenew";
//$myarray=Array ( [keynew] => valuenew [key1] => value1 [key2] => value2 ) 

Thank you.

Community
  • 1
  • 1
ihtus
  • 2,673
  • 13
  • 40
  • 58

3 Answers3

3

Try the following:

<?php
$myArray  = array('key1' => 'value1', 'key2' => 'value2');
$myArray2 = array('keynew' => 'valuenew');
var_dump($myArray2 + $myArray);

Output:

% php test.php 
array(3) {
  ["keynew"]=>
  string(8) "valuenew"
  ["key1"]=>
  string(6) "value1"
  ["key2"]=>
  string(6) "value2"
}
deizel.
  • 11,042
  • 1
  • 39
  • 50
1

You could try using array_merge() function - it merges arrays while preserving order.

<?php
$myarray = array_merge(array('keynew' => '-valuenew'), $myarray);
Konrad Borowski
  • 11,584
  • 3
  • 57
  • 71
0

Have you looked into array_merge yet? I think that would help you out: http://php.net/manual/en/function.array-merge.php

pivot
  • 105
  • 7