在PHP8中向数组添加元素-PHP8知识详解

php8中向数组添加元素有多种方法,在这里主要讲解几个常用的方法:使用方括号\[\]添加元素、使用array_unshift()函数,向数组的头部添加元素、使用array_push()函数,向数组的尾部添加元素、使用array_splice()函数添加元素。

1、使用方括号\[\]添加元素:

使用方括号[]添加元素,参考代码:

复制代码
<?php   
$Array = [1, 2, 3];  
$Array[] = 4; // 在数组末尾添加元素  
$Array[] = 5; // 在数组末尾添加元素  
echo "<pre>";
print_r($Array);
?>

以上代码在php8中运行结果如下:

复制代码
Array
(
    [0] => 1
    [1] => 2
    [2] => 3
    [3] => 4
    [4] => 5
)

2、使用array_unshift()函数,向数组的头部添加元素

语法格式如下:

复制代码
array_unshift(目标数组,元素1,元素2,元素n)

使用array_unshift()函数,向数组的头部添加一个或者多个元素,示范代码如下:

复制代码
<?php     
$Array = ["https://www.phpfw.com/tag/html/", "css", "https://www.phpfw.com/tag/java/script"];   
array_unshift($Array, "php", "https://www.phpfw.com/tag/mysql/");// 在数组头部添加多个元素    
echo "<pre>";  
print_r($Array);  
?>

在PHP8中运行结果如下:

复制代码
Array
(
    [0] => php
    [1] => mysql
    [2] => html
    [3] => css
    [4] => javascript
)

3、使用array_push()函数,向数组的尾部添加元素

语法格式如下:

复制代码
array_push(目标数组,元素1,元素2,元素n)

使用array_push()函数,向数组的尾部添加元素,参考代码:

复制代码
<?php   
$Array = [1, 2, 3];  
array_push($Array, 4, 5); // 在数组末尾添加多个元素  
echo "<pre>";
print_r($Array);
?>

以上代码在PHP8中的运行结果如下:

复制代码
Array
(
    [0] => 1
    [1] => 2
    [2] => 3
    [3] => 4
    [4] => 5
)

4、使用array_splice()函数添加元素

使用array_splice()函数添加元素,语法格式如下:

复制代码
array_splice(array,offset,length,array)

array 必需。规定数组。

offset 必需。数值。如果 offset 为正,则从输入数组中该值指定的偏移量开始移除。如果 offset 为负,则从输入数组末尾倒数该值指定的偏移量开始移除。

length 可选。数值。如果省略该参数,则移除数组中从 offset 到 结尾的所有部分。如果指定了 length 并且为正值,则移除这么多元素。如果指定了 length 且为负值,则移除从 offset 到数组末尾倒数 length 为止中间所有的元素。

array 被移除的元素由此数组中的元素替代。如果没有移除任何值,则此数组中的元素将插入到指定位置。

示范代码:

复制代码
<?php     
$Array = [1, 2, 3, 4, 5];  
  
// 添加元素到数组的末尾  
$element = 6;  
array_splice($Array, https://www.phpfw.com/tag/count/($Array), 0, $element);  
  
// 在指定位置添加元素  
$index = 2;  
$element = 7;  
array_splice($Array, $index, 0, $element);  
echo "<pre>";  
print_r($Array);
?>

以上代码在PHP8中的运行结果为:

复制代码
Array
(
    [0] => 1
    [1] => 2
    [2] => 7
    [3] => 3
    [4] => 4
    [5] => 5
    [6] => 6
)

到此为止,在PHP8中向数组添加元素有多种方法,在这里主要讲解几个常用的方法:使用方括号\[\]添加元素、使用array_unshift()函数,向数组的头部添加元素、使用array_push()函数,向数组的尾部添加元素、使用array_splice()函数添加元素。已经讲解完毕。

相关推荐
ID34610744201 小时前
【课程设计】基于Spring Boot+Vue的校园共享无人机服务系统设计与实现-计算机毕设 附源码44219
javascript·vue.js·spring boot·python·node.js·php·课程设计
sbjdhjd3 小时前
ThinkPHP 5.0.10 缓存写入型 RCE 复盘:从手动搭建、换行绕过到源码单步验证 | 05
java·后端·安全·spring·网络安全·数据挖掘·php
en.en..3 小时前
TCP/UDP 收发流程(网络字节序---函数讲解)
开发语言·php
en.en..4 小时前
TCP/IP四层模型「数据包封装与拆包」| 网络传输
服务器·网络·php
aixingpan7 小时前
aixingpan.cn API开发文档:api_docs_trichart_natal_progression_ter_transit2接口指南
前端·php
gf13211117 小时前
python_调用远程服务器上的openclaw
服务器·python·php
czt_java8 小时前
网络核心初识:OSI七层、TCP/IP模型与数据传输全过程
网络·tcp/ip·php
Lysander.Jovian8 小时前
OpenStack使用_网页版
php·openstack
siner.li8 小时前
Mac通过brew安装的PHP8.0,编译安装swoole4
php
疯狂打码的少年20 小时前
【计算机网络】子网掩码与子网划分计算(含CIDR表示法)
服务器·笔记·计算机网络·php