Home  >  Article  >  Backend Development  >  How to add elements to the end of a two-dimensional array in php

How to add elements to the end of a two-dimensional array in php

青灯夜游
青灯夜游Original
2022-04-26 18:29:143453browse

Methods to add elements: 1. Use the array_push() function, the syntax "array_push(two-dimensional array, value 1, value 2...);"; 2. Use the array_splice() function, the syntax "array_splice (two-dimensional array, count (two-dimensional array), 0, element value)".

How to add elements to the end of a two-dimensional array in php

The operating environment of this tutorial: windows7 system, PHP7.1 version, DELL G3 computer

php in 2D Methods to add elements to the end of the array

1. Use the array_push() function

The array_push() function can insert one or more elements at the end of the array element (key value).

<?php
header(&#39;content-type:text/html;charset=utf-8&#39;);   
$arr=$array = array(
    array("张三",25,"男"),
    array("李四",21,"男"),
    array("娜娜",22,"女")
);
var_dump($arr);
array_push($arr,"hello");
var_dump($arr);
?>

How to add elements to the end of a two-dimensional array in php

The added element can also be an array type:

array_push($arr,array("李华",22,"男"));

How to add elements to the end of a two-dimensional array in php

##2. Use array_splice( )Function

array_splice() function is a powerful function that can be used to delete array elements, replace array elements, and also insert array elements (just set the parameter $length to 0 That’s it).

When $length=0, then the parameter $start can specify the position (subscript) to start inserting, and the parameter $value can specify the insertion value (if there are multiple values, it needs to be set as an array).

If you want to insert an element at the end of the array, you only need to set the value of $start to the "array length value", that is, count($arr).

<?php
header(&#39;content-type:text/html;charset=utf-8&#39;);   
$arr=$array = array(
    array("张三",25,"男"),
    array("李四",21,"男"),
    array("娜娜",22,"女")
);
var_dump($arr);
array_splice($arr,count($arr),0,"hello");
var_dump($arr);
?>

How to add elements to the end of a two-dimensional array in php

If you want to add multiple elements, you can set the four parameters to array types

array_splice($arr,count($arr),0,array("1",25,"3"));

How to add elements to the end of a two-dimensional array in php

Recommended learning : "

PHP Video Tutorial"

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

Statement:
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