How to add elements to php array array

青灯夜游
Release: 2023-03-13 14:26:01
Original
3891 people have browsed it

增加方法:1、用“array_unshift($arr,值)”语句;2、用“array_push($arr,值)”语句;3、用“array_pad($arr,数组长度,值)”语句;4、用“array_splice($arr,0,0,值)”。

How to add elements to php array array

本教程操作环境:windows7系统、PHP7.1版、DELL G3电脑

php array数组增加元素

1、使用array_unshift()函数在数组开头插入一个或多个新元素

<?php
$arr=array(10,12,20);
array_unshift($arr,8,"9");
var_dump($arr);
?>
Copy after login

输出结果:

How to add elements to php array array

2、使用array_push()函数在数组尾部插入一个或多个新元素

<?php
$arr=array(10,12,20);
array_push($arr,8,"9",3.14);
var_dump($arr);
?>
Copy after login

输出结果为:

How to add elements to php array array

3、使用array_pad()函数在数组中插入新元素

array_pad($array,$size,$value)函数可以将某个键值$value插入到数组$array中,从而将数组填补到指定的长度$size。($size参数可以理解为数组中元素的最终数目,即插入操作后的数组长度)。

<?php
$arr=array(10,12,20);
$result =array_pad($arr,5,1);
var_dump($result);
?>
Copy after login

输出结果为:

How to add elements to php array array

4、使用array_splice()函数在数组中插入新元素

array_splice($array,$start,$length,$value)函数是一个强大的函数,可以用来删除数组元素、替换数组元素,也能用来插入数组元素(只需要将参数$length的设置为0即可)。

当$length=0,那么参数$start就可指定开始插入的位置(下标),参数$value就可指定插入值(如果是多个值就需要设置为数组)。

<?php
header("Content-type:text/html;charset=utf-8");
$arr1=array(10,12,20);
array_splice($arr1,0,0,"1");
var_dump($arr1);

$arr2=array(10,12,20);
array_splice($arr2,0,0,array("1",25,"3"));
var_dump($arr2);
?>
Copy after login

输出结果为:

How to add elements to php array array

推荐学习:《PHP视频教程

The above is the detailed content of How to add elements to php array array. For more information, please follow other related articles on the PHP Chinese website!

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
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!