How do you insert an element into an array at a specific index php?

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 I insert an array at a specific index?

Algorithm.
Get the element value which needs to be inserted..
Get the position value..
Check whether the position value is valid or not..
If it is valid, Shift all the elements from the last index to position index by 1 position to the right. insert the new element in arr[position].
Otherwise,.

How do you insert an element in an array at any position in PHP?

A simple solution to insert an item at a specific position in an array is using the array_slice() function. The idea is to extract a slice of the array using array_slice() function and then recombine the parts using the array_merge() function.

How do you add value to a specific index?

add() method is used to add an element at particular index in Java ArrayList.