Method: 1. Use the array_unshift() function to add an element to the beginning of the array, the syntax is "array_unshift(array, value)"; 2. Use the array_push() function to add an element to the end of the array, the syntax is " array_push(array,value)".
The operating environment of this tutorial: windows7 system, PHP7.1 version, DELL G3 computer
Add elements at the head of the array
The array_unshift() function adds elements to the head of the array. All existing numeric keys are modified to reflect their new positions in the array, but associated keys are not affected. Its form is as follows:
array_unshift(array array,mixed variable[,mixed variable])
The following example adds two fruits in front of the $fruits array:
$fruits = array("apple","banana"); array_unshift($fruits,"orange","pear") // $fruits = array("orange","pear","apple","banana");
Add elements at the end of the array
array_push The () function adds (push) one or more elements to the end of the first argument's array and returns the length of the new array.
The return value of the array_push() function is int type, which is the number of elements in the array after pushing the data. You can pass multiple variables as parameters to this function and push multiple variables into the array at the same time. Its form is:
array_push(array,value1,value2...)
The following example adds two more fruits to the $fruits array:
view sourceprint? $fruits = array("apple","banana"); array_push($fruits,"orange","pear") //$fruits = array("apple","banana","orange","pear")
Recommended learning: "PHP Video Tutorial"
The above is the detailed content of How to add an element to a php array. For more information, please follow other related articles on the PHP Chinese website!