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

How to add elements to an array in php

藏色散人
藏色散人Original
2018-11-27 10:51:019294browse

This article mainly introduces how to add elements to an array in .

Adding an element to a PHP array means adding a new item to the array. So it may be difficult for beginners.

Below we will use specific code examples to explain how to add elements at any position in a PHP array.

The code is as follows:

";
foreach ($original as $x)
{
    echo "$x ";
}
echo "
"; $inserted = '¥'; array_splice( $original, 3, 0, $inserted ); echo " 添加 '¥' 后的新数组是 : "."
"; foreach ($original as $x) { echo "$x "; }

The result is as shown below:

How to add elements to an array in php

##array_splice syntax:

array_splice(array,start,length,array)

array_splice function means to remove a certain part of the array and replace it with other values. That is, remove the selected element from the array and replace it with the new element.

What needs to be noted here is that if the function does not remove any elements (when length is the third parameter is 0), the replaced array will be inserted from the position of start (the second parameter).

Note: The key names in the replaced array are not retained.

So as shown in the picture above, a new element ¥ is added to the PHP array. Of course, we can add new elements at any position.

This article is an introduction to how to add elements to an array in PHP. It is very simple and easy to understand. I hope it will be helpful to friends in need!

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