Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to insert element into arrays at specific position?

Tags:

arrays

php

People also ask

How do you push an element to an array at first position?

The unshift() method adds new elements to the beginning of an array.

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

Inserting an element in list at specific index using list. insert() In python list provides a member function insert() i.e. It accepts a position and an element and inserts the element at given position in the list.

How can you add a new element at the 0th index of an array?

You want to explicitly add it at a particular place of the array. That place is called the index. Array indexes start from 0 , so if you want to add the item first, you'll use index 0 , in the second place the index is 1 , and so on. To perform this operation you will use the splice() method of an array.


array_slice() can be used to extract parts of the array, and the union array operator (+) can recombine the parts.

$res = array_slice($array, 0, 3, true) +
    array("my_key" => "my_value") +
    array_slice($array, 3, count($array)-3, true);

This example:

$array = array(
  'zero'  => '0',
  'one'   => '1',
  'two'   => '2',
  'three' => '3',
);
$res = array_slice($array, 0, 3, true) +
    array("my_key" => "my_value") +
    array_slice($array, 3, count($array) - 1, true) ;
print_r($res);

gives:

Array
(
    [zero] => 0
    [one] => 1
    [two] => 2
    [my_key] => my_value
    [three] => 3
)

For your first array, use array_splice():

$array_1 = array(
  '0' => 'zero',
  '1' => 'one',
  '2' => 'two',
  '3' => 'three',
);

array_splice($array_1, 3, 0, 'more');
print_r($array_1);

output:

Array(
    [0] => zero
    [1] => one
    [2] => two
    [3] => more
    [4] => three
)

for the second one there is no order so you just have to do :

$array_2['more'] = '2.5';
print_r($array_2);

And sort the keys by whatever you want.


code:

function insertValueAtPosition($arr, $insertedArray, $position) {
    $i = 0;
    $new_array=[];
    foreach ($arr as $key => $value) {
        if ($i == $position) {
            foreach ($insertedArray as $ikey => $ivalue) {
                $new_array[$ikey] = $ivalue;
            }
        }
        $new_array[$key] = $value;
        $i++;
    }
    return $new_array;
}

example:

$array        = ["A"=8, "K"=>3];
$insert_array = ["D"= 9];

insertValueAtPosition($array, $insert_array, $position=2);
// result ====> ["A"=>8,  "D"=>9,  "K"=>3];

May not really look perfect, but it works.


Here's a simple function that you could use. Just plug n play.

This is Insert By Index, Not By Value.

you can choose to pass the array, or use one that you already have declared.

EDIT: Shorter Version:

   function insert($array, $index, $val)
   {
       $size = count($array); //because I am going to use this more than one time
       if (!is_int($index) || $index < 0 || $index > $size)
       {
           return -1;
       }
       else
       {
           $temp   = array_slice($array, 0, $index);
           $temp[] = $val;
           return array_merge($temp, array_slice($array, $index, $size));
       }
   }

  function insert($array, $index, $val) { //function decleration
    $temp = array(); // this temp array will hold the value 
    $size = count($array); //because I am going to use this more than one time
    // Validation -- validate if index value is proper (you can omit this part)       
        if (!is_int($index) || $index < 0 || $index > $size) {
            echo "Error: Wrong index at Insert. Index: " . $index . " Current Size: " . $size;
            echo "<br/>";
            return false;
        }    
    //here is the actual insertion code
    //slice part of the array from 0 to insertion index
    $temp = array_slice($array, 0, $index);//e.g index=5, then slice will result elements [0-4]
    //add the value at the end of the temp array// at the insertion index e.g 5
    array_push($temp, $val);
    //reconnect the remaining part of the array to the current temp
    $temp = array_merge($temp, array_slice($array, $index, $size)); 
    $array = $temp;//swap// no need for this if you pass the array cuz you can simply return $temp, but, if u r using a class array for example, this is useful. 

     return $array; // you can return $temp instead if you don't use class array
}

Now you can test the code using

//1
$result = insert(array(1,2,3,4,5),0, 0);
echo "<pre>";
echo "<br/>";
print_r($result);
echo "</pre>";
//2
$result = insert(array(1,2,3,4,5),2, "a");
echo "<pre>";
print_r($result);
echo "</pre>";
//3
$result = insert(array(1,2,3,4,5) ,4, "b");
echo "<pre>";
print_r($result);
echo "</pre>";
//4
$result = insert(array(1,2,3,4,5),5, 6);
echo "<pre>";
echo "<br/>";
print_r($result);
echo "</pre>";

And the result is :

//1
Array
(
    [0] => 0
    [1] => 1
    [2] => 2
    [3] => 3
    [4] => 4
    [5] => 5
)
//2
Array
(
    [0] => 1
    [1] => 2
    [2] => a
    [3] => 3
    [4] => 4
    [5] => 5
)
//3
Array
(
    [0] => 1
    [1] => 2
    [2] => 3
    [3] => 4
    [4] => b
    [5] => 5
)

//4
Array
(
    [0] => 1
    [1] => 2
    [2] => 3
    [3] => 4
    [4] => 5
    [5] => 6
)

$list = array(
'Tunisia' => 'Tunis',
'Germany' => 'Berlin',
'Italy' => 'Rom',
'Egypt' => 'Cairo'
);
$afterIndex = 2;
$newVal= array('Palestine' => 'Jerusalem');

$newList = array_merge(array_slice($list,0,$afterIndex+1), $newVal,array_slice($list,$afterIndex+1));

This function supports:

  • both numeric and assoc keys
  • insert before or after the founded key
  • append to the end of array if key isn't founded

function insert_into_array( $array, $search_key, $insert_key, $insert_value, $insert_after_founded_key = true, $append_if_not_found = false ) {

        $new_array = array();

        foreach( $array as $key => $value ){

            // INSERT BEFORE THE CURRENT KEY? 
            // ONLY IF CURRENT KEY IS THE KEY WE ARE SEARCHING FOR, AND WE WANT TO INSERT BEFORE THAT FOUNDED KEY
            if( $key === $search_key && ! $insert_after_founded_key )
                $new_array[ $insert_key ] = $insert_value;

            // COPY THE CURRENT KEY/VALUE FROM OLD ARRAY TO A NEW ARRAY
            $new_array[ $key ] = $value;

            // INSERT AFTER THE CURRENT KEY? 
            // ONLY IF CURRENT KEY IS THE KEY WE ARE SEARCHING FOR, AND WE WANT TO INSERT AFTER THAT FOUNDED KEY
            if( $key === $search_key && $insert_after_founded_key )
                $new_array[ $insert_key ] = $insert_value;

        }

        // APPEND IF KEY ISNT FOUNDED
        if( $append_if_not_found && count( $array ) == count( $new_array ) )
            $new_array[ $insert_key ] = $insert_value;

        return $new_array;

    }

USAGE:

    $array1 = array(
        0 => 'zero',
        1 => 'one',
        2 => 'two',
        3 => 'three',
        4 => 'four'
    );

    $array2 = array(
        'zero'  => '# 0',
        'one'   => '# 1',
        'two'   => '# 2',
        'three' => '# 3',
        'four'  => '# 4'
    );

    $array3 = array(
        0 => 'zero',
        1 => 'one',
       64 => '64',
        3 => 'three',
        4 => 'four'
    );


    // INSERT AFTER WITH NUMERIC KEYS
    print_r( insert_into_array( $array1, 3, 'three+', 'three+ value') );

    // INSERT AFTER WITH ASSOC KEYS
    print_r( insert_into_array( $array2, 'three', 'three+', 'three+ value') );

    // INSERT BEFORE
    print_r( insert_into_array( $array3, 64, 'before-64', 'before-64 value', false) );

    // APPEND IF SEARCH KEY ISNT FOUNDED
    print_r( insert_into_array( $array3, 'undefined assoc key', 'new key', 'new value', true, true) );

RESULTS:

Array
(
    [0] => zero
    [1] => one
    [2] => two
    [3] => three
    [three+] => three+ value
    [4] => four
)
Array
(
    [zero] => # 0
    [one] => # 1
    [two] => # 2
    [three] => # 3
    [three+] => three+ value
    [four] => # 4
)
Array
(
    [0] => zero
    [1] => one
    [before-64] => before-64 value
    [64] => 64
    [3] => three
    [4] => four
)
Array
(
    [0] => zero
    [1] => one
    [64] => 64
    [3] => three
    [4] => four
    [new key] => new value
)

Simplest solution, if you want to insert (an element or array) after a certain key:

function array_splice_after_key($array, $key, $array_to_insert)
{
    $key_pos = array_search($key, array_keys($array));
    if($key_pos !== false){
        $key_pos++;
        $second_array = array_splice($array, $key_pos);
        $array = array_merge($array, $array_to_insert, $second_array);
    }
    return $array;
}

So, if you have:

$array = [
    'one' => 1,
    'three' => 3
];
$array_to_insert = ['two' => 2];

And execute:

$result_array = array_splice_after_key($array, 'one', $array_to_insert);

You'll have:

Array ( 
    ['one'] => 1 
    ['two'] => 2 
    ['three'] => 3 
)