Home > Backend Development > PHP Tutorial > php怎么在数组指定位置插入元素?

php怎么在数组指定位置插入元素?

PHPz
Release: 2020-06-24 09:58:26
Original
6456 people have browsed it

php怎么在数组指定位置插入元素?

php怎么在数组指定位置插入元素?

使用array_splice() 函数

<?php
$array1 = array(&#39;a&#39;, &#39;b&#39;, &#39;c&#39;, &#39;d&#39;, &#39;e&#39;);
$array2 = array(&#39;x&#39;);
array_splice($array1, 3, 0, $array2); // 插入到位置3且删除0个
print_r($array1);
?>
Copy after login

输出:

Array
(
    [0] => a
    [1] => b
    [2] => c
    [3] => x
    [4] => d
    [5] => e
)
Copy after login

array_splice() 函数从数组中移除选定的元素,并用新元素取代它。函数也将返回被移除元素的数组。

提示:如果函数没有移除任何元素(length=0),则替代数组将从 start 参数的位置插入、。

注释:不保留替代数组中的键名。

语法

array_splice(array,start,length,array)
Copy after login

1.png

拓展知识:

使用array_push() 函数

array_push() 函数向数组尾部插入一个或多个元素,然后返回新数组的长度。

示例:向数组尾部插入 "blue" 和 "yellow":

<?php
$a=array("red","green");array_push($a,"blue","yellow");
print_r($a);
?>
Copy after login

输出:

Array ( [0] => red [1] => green [2] => blue [3] => yellow )
Copy after login

推荐教程:PHP视频教程

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template