Author: Admin 09/09/2023
Language:
PHP
Tags: array php insert array_splice
This function removes a portion of an array and replaces it with something else. If offset and length are such that nothing is removed, then the elements from the replacement array are inserted in the place specified by the offset.
Syntax
array array_splice ($input, $offset [, $length [, $replacement]])
Parameters: This function takes four parameters out of which 2 are mandatory and 2 are optional:
<?php
//Original Array on which operations is to be perform
$original_array = array( '1', '2', '3', '4', '5' );
echo 'Original array : ';
foreach ($original_array as $x)
{
echo "$x ";
}
echo "\n";
//value of new item
$inserted_value = '11';
//value of position at which insertion is to be done
$position = 2;
//array_splice() function
array_splice( $original_array, $position, 0, $inserted_value );
echo "After inserting 11 in the array is : ";
foreach ($original_array as $x)
{
echo "$x ";
}
Original array : 1 2 3 4 5
After inserting 11 in the array is : 1 2 11 3 4 5
Read More at Program to Insert new item in array on any position in PHP - GeeksforGeeks