Home >Backend Development >PHP Problem >How to add an element to a php array

How to add an element to a php array

青灯夜游
青灯夜游Original
2021-05-28 17:28:184563browse

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)".

How to add an element to a php array

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!

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