Home >Backend Development >PHP Problem >How to add elements to an array in php

How to add elements to an array in php

WBOY
WBOYOriginal
2021-12-02 09:45:065103browse

In PHP, you can use the "array_push()" function to add elements to an array. This function can add one or more elements to the end of the array and return the length of the new array. The syntax is "array_push() array,value1,value2...)".

How to add elements to an array in php

The operating environment of this tutorial: windows7 system, PHP7.1 version, DELL G3 computer

How to add php to an array Add elements inside

In PHP, you can use the array_push() function to add elements to an array. An example is as follows:

array_push() function adds one or more elements (push) to the end of the array of the first parameter, and then returns the length of the new array.

1. Create a new php file, named test.php, to explain how to add an element to the php array. Use the header() method to set the encoding format of the page to utf-8 to avoid outputting Chinese garbled characters. Create an array with two elements in the array. Save the array element to be added in the $str variable.

How to add elements to an array in php

2. In the test.php file, use the array_push() function to add the $str element to the $arr array, and at the same time, use print_r() to output the elements of the array. .

How to add elements to an array in php

Open the test.php file in the browser to view the results.

How to add elements to an array in php

Summary:

1. Create an array with two elements in the array.

2. Save the array element to be added in the $str variable.

3. Use the array_push() function to add the $str element to the $arr array, and at the same time, use print_r() to output the elements of the array.

If you are interested, you can click on "PHP Video Tutorial" to learn more about PHP knowledge.

The above is the detailed content of How to add elements to an array in php. 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