How to add an element to php array

PHPz
Release: 2023-04-26 09:45:52
Original
769 people have browsed it

In PHP, adding an element to an array is very simple. The following two methods can be used:

Method 1: Use the array_push() function

The array_push() function adds one or more elements to the end of the array. The syntax is as follows:

array_push($array, $element1, $element2, ...);
Copy after login

Among them, $array is the array to which elements are to be added, $element1, $element2 are the elements to be added. Multiple elements can be added up to the last parameter.

For example, add an element to the array:

$arr = array("red", "green", "blue"); array_push($arr, "yellow"); print_r($arr);
Copy after login

The output is:

Array ( [0] => red [1] => green [2] => blue [3] => yellow )
Copy after login
Copy after login

Method 2: Use the [] operator

In PHP, The [] operator can be used to add elements to the end of an array. The syntax is as follows:

$array[] = $element;
Copy after login

Among them, $array is the array to which elements are to be added, and $element is the element to be added.

For example, adding an element to an array:

$arr = array("red", "green", "blue"); $arr[] = "yellow"; print_r($arr);
Copy after login

The output is:

Array ( [0] => red [1] => green [2] => blue [3] => yellow )
Copy after login
Copy after login

Summary

Both of the above methods can be used in PHP Add an element to the array. The array_push() function can add one or more elements, while the [] operator can only add one element. Which method you choose depends on your specific needs.

The above is the detailed content of How to add an element to php array. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
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
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!