php method to add data to an array: 1. Use the "array_unshift(array, data value 1, data value 2...)" statement; 2. Use "array_push(array, value 1, value 2. ..)" statement; 3. Use the "array_splice(array, starting position, 0, value)" statement.
The operating environment of this tutorial: windows7 system, PHP7.1 version, DELL G3 computer
php adds to the array Data
Method 1: array_unshift() function
##array_unshift($array,$value1,$value2...)The function can insert one or more new elements (key values) at the beginning of the array.
<?php $arr=array(10,12,20); array_unshift($arr,8,"9"); var_dump($arr); ?>
Method 2: array_push() function
array_push($array,$value1,$value2.. .)The function can insert one or more elements (key values) at the end of the array.
<?php $arr=array(10,12,20); array_push($arr,8,"9",3.14); var_dump($arr); ?>
Method 3: array_splice() function
array_splice($array,$start,$length,$ value) 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).
$length=0, then the parameter $start can specify the position (subscript) to start inserting, and the parameter
$value can specify the insertion value (if If it is multiple values, it needs to be set as an array).
<?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); ?>
Method 4: array_pad() function
array_pad($array,$size,$value)The function can insert a certain key value
$value into the array
$array, thereby filling the array to the specified length
$size. (The
$size parameter can be understood as the final number of elements in the array, that is, the length of the array after the insertion operation).
<?php $arr=array(10,12,20); $result =array_pad($arr,5,1); var_dump($result); ?>
array_pad($arr,5,1) that the value of $size is 5, then there are a total of 5 elements in the array after the insertion operation; and the original There are 3 elements, so only 2 elements need to be inserted. And because the inserted value $value is 1, you only need to insert 2 elements with the value "1". Therefore, the output result is:
PHP Video Tutorial"
The above is the detailed content of How to add data to an array in php. For more information, please follow other related articles on the PHP Chinese website!