如何在数组中插入元素在中间


How to insert element in array in the middle

我不知道如何用php在数组中间插入元素。我知道它在c++或c#中是如何求解的,但在php中我不知道。请帮帮我。

我使用

$stack = array("orange", "banana");
array_push($stack, "apple", "raspberry");
print_r($stack);

但这个加法运算的起始点不是中间。

使用array_splice():

array_splice($stack, 1, 0, array("apple", "raspberry"));

指定长度为0意味着它应该只在该位置插入新元素,而不删除任何内容。

如果您只是在数组中插入一个元素,则不需要将其封装在数组中:

array_splice($stack, 1, 0, "apple");
$stack = array("orange", "banana");
$inserted = array("apple", "raspberry");
$position = 1;
array_splice( $stack, $position, 0, $inserted );