Home > Article > Backend Development > How to add elements to the end of a two-dimensional array in php
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)".
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('content-type:text/html;charset=utf-8'); $arr=$array = array( array("张三",25,"男"), array("李四",21,"男"), array("娜娜",22,"女") ); var_dump($arr); array_push($arr,"hello"); var_dump($arr); ?>
The added element can also be an array type:
array_push($arr,array("李华",22,"男"));
##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('content-type:text/html;charset=utf-8'); $arr=$array = array( array("张三",25,"男"), array("李四",21,"男"), array("娜娜",22,"女") ); var_dump($arr); array_splice($arr,count($arr),0,"hello"); var_dump($arr); ?>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"));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!