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

How to add elements to an array in php

藏色散人
Release: 2023-04-04 13:34:02
Original
9436 people have browsed it

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( &#39;1&#39;,&#39;2&#39;,&#39;3&#39;,&#39;4&#39;,&#39;5&#39; );
echo &#39;原始数组 :&#39;."<br>";
foreach ($original as $x)
{
    echo "$x ";
}
echo "<br>";
$inserted = &#39;¥&#39;;
array_splice( $original, 3, 0, $inserted );
echo " 添加 &#39;¥&#39; 后的新数组是 : "."<br>";
foreach ($original as $x)
{
    echo "$x ";
}
Copy after login

The result is as shown below:

How to add elements to an array in php

##array_splice syntax:

array_splice(array,start,length,array)
Copy after login

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!

Related labels:
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template