How to insert data unit at specified position in array in php

王林
Release: 2023-04-07 20:16:02
forward
5271 people have browsed it

How to insert data unit at specified position in array in php

Method:

Use the array_splice() function.

Syntax format:

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

Parameters:

array: Required. Specifies an array.

offset: required. numerical value. If offset is positive, removal begins at the offset specified by this value in the input array. If offset is negative, removal begins at the offset specified by this value from the end of the input array.

length: Optional. numerical value. If this parameter is omitted, all parts of the array from offset to the end are removed. If length is specified and is positive, this many elements are removed. If length is specified and is negative, all elements from offset to length counting down from the end of the array are removed.

array: The removed elements are replaced by elements in this array. If no values ​​are removed, the element in this array is inserted at the specified position.

Example one:

<?php
$a1=array(0=>"Dog",1=>"Cat",2=>"Horse",3=>"Bird");
$a2=array(0=>"Tiger",1=>"Lion");
array_splice($a1,0,2,$a2);
print_r($a1);
?>
Copy after login

Result:

Array ( [0] => Tiger [1] => Lion [2] => Horse [3] => Bird )
Copy after login

Example two:

<?php
$a1=array(0=>"Dog",1=>"Cat");
$a2=array(0=>"Tiger",1=>"Lion");
array_splice($a1,1,0,$a2);
print_r($a1);
?>
Copy after login

Result:

Array ( [0] => Dog [1] => Tiger [2] => Lion [3] => Cat )
Copy after login

Recommended tutorial: php tutorial

The above is the detailed content of How to insert data unit at specified position in array in php. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:csdn.net
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