使用 Union 运算符在数组开头插入 - 新元素覆盖数组的(先前)第一个元素

Insertion at the beginning of array using Union Operator - new element is Overwriting the (previously) first element of the array

以下 SSCCE 打印:

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

我想要的:

我想要的是在数组的开头插入一个值为 "flat" 的元素,即我希望在索引 0 处插入 "flat",并且其余元素应向右移动一个位置,以便为数组开头的插入提供空闲位置。

所以我尝试使用联合运算符。 source

我得到的是:

但实际发生的是数组的第一个元素"id"被新插入的元素over-written/replaced

问题是为什么会这样,我应该怎么做才能达到我的需要?

$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);

使用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 )

来自手册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.

尝试array_unshift()修改数组:

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

array_merge():

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

使用 array_unshift 将元素添加到数组的开头。

$arr=array( [0] => 平面 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