6

I got the following array:

$arr = array(6 => 'Somedata', 7 => 'Somedata1', 8 => 'Somedata2');

The problem is that, when I use array_merge( (array) "Select the data", $arr);, it does change the array keys into:

Array
(
    [0] => Not specified
    [1] => Somedata
    [2] => Somedata1
    [3] => Somedata2
)

Is that possible to skip the array_merge key preversion so the output would look like this?

Array
(
    [0] => Not specified
    [6] => Somedata
    [7] => Somedata1
    [8] => Somedata2
)
Sapp
  • 624
  • 2
  • 7
  • 13
  • please show us the code. `array_merge` is [preserving keys by default](http://codepad.org/I9YcWzdl) – Peter Sep 12 '12 at 23:46
  • @EXQStudio The code is in the second line of my question, there is a simple `array_merge( (array) "Select the data", $arr);` after, and `print_r` dump after that. – Sapp Sep 12 '12 at 23:48
  • why do you cast string as array? Why not `Array("Select the data")`? – Peter Sep 12 '12 at 23:49
  • Array_merge preserves keys from the first array, couldn't you get the result you are after be switching the arrays around like: `array_merge($arr, (array) "Select the data");` ? – Fluffeh Sep 12 '12 at 23:51
  • @EXQStudio Why not? See the http://php.net/manual/en/function.array-merge.php Example #1, its not forbidden, and working fine. – Sapp Sep 12 '12 at 23:51

1 Answers1

11

Use the + operator to create a union of the 2 arrays:

$arr = array(6 => 'Somedata', 7 => 'Somedata1', 8 => 'Somedata2');

$result = (array)'Select the data' + $arr;

var_dump($result);

Result:

array(4) {
  [0]=>
  string(15) "Select the data"
  [6]=>
  string(8) "Somedata"
  [7]=>
  string(9) "Somedata1"
  [8]=>
  string(9) "Somedata2"
}
drew010
  • 68,777
  • 11
  • 134
  • 162
Jirka Kopřiva
  • 2,939
  • 25
  • 28
  • Be careful though, this can overwrite data if they arrays have the same key. Try running it with `$arr = array(0 => 'Somedata', 7 => 'Somedata1', 8 => 'Somedata2');` as the input. – Fluffeh Sep 12 '12 at 23:57