0

The following SSCCE prints:

Array ( [0] => FLAT [1] => A [2] => B [3] => C [4] => D [5] => E [6] => F [7] => G [8] => H [9] => I [10] => J )

What I wanted:

What I wanted was to insert an element with a value of "flat" at the start of the array, i.e. I wanted "flat" to be inserted at index 0, and the rest of the elements should move right by one position to give free position for the insertion at the beginning of the array.

So I tried to use the union operator. source

What I got:

But what actually happened was that the first element of the array, "id", was over-written/replaced by the newly inserted element.

The question is that why is this happening, and what should I do to achieve what I need?

$array = array(
  0 => "id",
  1 => "A",
  2 => "B",
  3 => "C",
  4 => "D",
  5 => "E",
  6 => "F",
  7 => "G",
  8 => "H",
  9 => "I",
  10 => "J"
);

$arrayNew = array("flat") + $array;

print_r($array_new);
Community
  • 1
  • 1
Solace
  • 8,612
  • 22
  • 95
  • 183

3 Answers3

2

From the manual Array Operators:

The + operator returns the right-hand array appended to the left-hand array; for keys that exist in both arrays, the elements from the left-hand array will be used, and the matching elements from the right-hand array will be ignored.

Try array_unshift() to modify the array:

array_unshift($array, array("flat"));

Or array_merge():

$arrayNew = array_merge(array("flat"), $array);
AbraCadaver
  • 78,200
  • 7
  • 66
  • 87
1

Using array_merge()

$array = array(
  0 => "id",
  1 => "A",
  2 => "B",
  3 => "C",
  4 => "D",
  5 => "E",
  6 => "F",
  7 => "G",
  8 => "H",
  9 => "I",
  10 => "J"
);

$arrayNew = array_merge(array("flat"), $array);

print_r($arrayNew);

Array ( [0] => flat [1] => id [2] => A [3] => B [4] => C [5] => D [6] => E [7] => F [8] => G [9] => H [10] => I [11] => J )

JustBaron
  • 2,319
  • 7
  • 25
  • 37
0

use array_unshift which will add elements to the beginning of the array.

$arr=array( [0] => FLAT 1 => A [2] => B [3] => C [4] => D [5] => E [6] => F [7] => G [8] => H [9] => I [10] => J );

array_unshift($arr, "flat");

php array_unshift manual

Hawk
  • 788
  • 1
  • 6
  • 18