Php insert into array at index

A function that can insert at both integer and string positions:

/**
 * @param array      $array
 * @param int|string $position
 * @param mixed      $insert
 */
function array_insert[&$array, $position, $insert]
{
    if [is_int[$position]] {
        array_splice[$array, $position, 0, $insert];
    } else {
        $pos   = array_search[$position, array_keys[$array]];
        $array = array_merge[
            array_slice[$array, 0, $pos],
            $insert,
            array_slice[$array, $pos]
        ];
    }
}

Integer usage:

$arr = ["one", "two", "three"];
array_insert[
    $arr,
    1,
    "one-half"
];
// ->
array [
  0 => 'one',
  1 => 'one-half',
  2 => 'two',
  3 => 'three',
]

String Usage:

$arr = [
    "name"  => [
        "type"      => "string",
        "maxlength" => "30",
    ],
    "email" => [
        "type"      => "email",
        "maxlength" => "150",
    ],
];

array_insert[
    $arr,
    "email",
    [
        "phone" => [
            "type"   => "string",
            "format" => "phone",
        ],
    ]
];
// ->
array [
  'name' =>
  array [
    'type' => 'string',
    'maxlength' => '30',
  ],
  'phone' =>
  array [
    'type' => 'string',
    'format' => 'phone',
  ],
  'email' =>
  array [
    'type' => 'email',
    'maxlength' => '150',
  ],
]

PHP Program to insert element into an array at specified position

It is a simple array program in PHP using an array, loop, and in-built function. Let's go through these topics to understand this program clearly

  • Array in PHP
  • Loops in PHP
  • Output methods of PHP

What is an array and how to insert elements to it?

An array is a data structure consisting of a collection of elements, each identified by at least one array index or key. The Elements are of the same data type.

To insert an element into an array we need an index or position where it is to be placed because elements are fetched using array index only. To add an element to the end of an array is easy but we need shifting of elements to insert an element in between of array. PHP provides an in-built function to insert elements, let's make use of it in our program.

How to insert into the array at a certain position using PHP?

In this program, we are going to insert an element at a specified index. For that, we first declare and assign values into the array arr[]. After that, we need a new value that is going to insert into the array, assign a value into the variable newValue. Then we have to specify the position where we have to insert the new element and assign that value into the variable pos. And to insert the element we are using the built-in function array_splice[]. In the function, we specify the array arr[], the position of the element in variable pos, and the newValue. And at last, we can print the elements of the array arr[] by using foreach loop.  

Syntax of array_splice[] function


array_splice[src_array, start_index, length, replace_array]
 

The array_splice[] function removes selected elements of size length from start_index of an array src_array and replaces them with new elements given in replace_array . The function also returns an array with the removed elements. 

NOTE: The function does not remove any elements [if length= 0], the replace_array will be inserted from the position of the start_index parameter.

ALGORITHM

Step 1: Initialize an array arr[] with values

Step 2: Print the element currently in the array arr[] using foreach loop

Step 3: Assign the new value to be inserted to the variable newValue

Step 4: Assign the position of the element to be inserted into the variable pos

Step 5: Call the built-in function array_splice[arr, pos,0,newValue]

Step 6: Print the elements in the array arr[] using foreach loop

PHP Source Code

                                          
                                      

OUTPUT

Array before inserting new element:
1 2 3 4 5
Array after inserting new element:
1 2 23 3 4 5

How do you array push to a specific index in PHP?

PHP array_push[] Function array_push[$a,"blue","yellow"]; print_r[$a];

How do you add an element to an array at a specific position?

Here's how to do it..
First get the element to be inserted, say x..
Then get the position at which this element is to be inserted, say pos..
Create a new array with the size one greater than the previous size..
Copy all the elements from previous array into the new array till the position pos..

What is Array_push in PHP?

The array_push[] is a built-in function of PHP. This function helps the users to add the elements at the end of the array. It allows to insert any number of elements in an array. Even you can add a string as well as numeric values.

What does Array_splice [] function do give an example?

The array_splice[] function removes selected elements from an array and replaces it with new elements. The function also returns an array with the removed elements. Tip: If the function does not remove any elements [length=0], the replaced array will be inserted from the position of the start parameter [See Example 2].

Chủ Đề