Home  >  Article  >  Backend Development  >  How to add an element to php array

How to add an element to php array

PHPz
PHPzOriginal
2023-04-26 09:16:28785browse

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, ...);

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);

The output is:

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

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;

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);

The output is:

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

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!

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