Home >Backend Development >PHP Tutorial >How to insert data unit at specified position in array in php

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

王林
王林forward
2019-11-19 17:58:455314browse

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)

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);
?>

Result:

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

Example two:

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

Result:

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

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!

Statement:
This article is reproduced at:csdn.net. If there is any infringement, please contact admin@php.cn delete