Home >Backend Development >PHP Tutorial >How to add elements to an array in php
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:
<?php $original = array( '1','2','3','4','5' ); echo '原始数组 :'."<br>"; foreach ($original as $x) { echo "$x "; } echo "<br>"; $inserted = '¥'; array_splice( $original, 3, 0, $inserted ); echo " 添加 '¥' 后的新数组是 : "."<br>"; foreach ($original as $x) { echo "$x "; }
The result is as shown below:
##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!