1

I am with an array like $x = array(1,2,3,4,5); i would like to add element 6 in between 3 and 4 and make it like array(1,2,3,6,4,5);

how do i make it in that place or first place?

BoltClock
  • 700,868
  • 160
  • 1,392
  • 1,356
KoolKabin
  • 17,157
  • 35
  • 107
  • 145

5 Answers5

2
array_insert($array,$pos,$val);

function array_insert($array,$pos,$val)
{
    $array2 = array_splice($array,$pos);
    $array[] = $val;
    $array = array_merge($array,$array2);

    return $array;
}
sushil bharwani
  • 29,685
  • 30
  • 94
  • 128
1

Try this:

$x = array(1,2,3,4,5);
$x = array_merge(array_slice($x, 0, 3), array(6), array_slice($x, 3));
print_r($x);

Output;

Array
(
    [0] => 1
    [1] => 2
    [2] => 3
    [3] => 6
    [4] => 4
    [5] => 5
)
codaddict
  • 445,704
  • 82
  • 492
  • 529
1

Use array_splice($array, $pos, 0, array($val)).

aib
  • 45,516
  • 10
  • 73
  • 79
  • `$length` is 0 by default; and this doesn't do what the OP asked for. This will replace the element in `$pos` with `$val`, not insert at `$pos`. – NullUserException Sep 26 '10 at 17:48
  • Take a look at Example #2. A `$length` of 0, though undocumented, causes insertion. I noticed `= 0` in the parameter list too, it must be an artifact. – aib Sep 26 '10 at 17:53
  • This does exactly what KoolKabin asked for, and doesn't replace any elements. But it's unnecessary to place the inserted value into an array. Also, this question seems to me an exact duplicate of this 9-hour-old question: http://stackoverflow.com/questions/3797239/php-array-insert-new-item-in-any-position/3797526#3797526 – GZipp Sep 26 '10 at 19:15
  • @GZipp: It is if you want to insert an array, object or NULL. – aib Sep 26 '10 at 22:08
  • Absolutely true, and since doing it that way makes the operation safer, I retract that part of my comment. – GZipp Sep 26 '10 at 23:18
0

It can by done like this:

function array_insert_value(array $array = array(), $value = null, $position = null)
{
    if(empty($position)) 
        return array_merge($array, array($value));
    else 
        return array_merge(
            array_slice($array, 0, $position),
            array($value),
            array_slice($array, $position)
        );    
}
Nazariy
  • 6,028
  • 5
  • 37
  • 61
0

I cam up with this function. I have also included the code I used for testing I hope this helps.

function chngNdx($array,$ndex,$val){
    $aCount = count($array);

    for($x=($aCount)-1;$x>=$ndex;$x--){
        $array[($x+1)] = $array[$x];
    }

    $array[$ndex] = $val;

    return $array;
}

$aArray = array();
$aArray[0] = 1;
$aArray[1] = 2;
$aArray[2] = 3;
$aArray[3] = 4;
$aArray[4] = 5;
$ndex =  3;     // # on the index to change 0-#
$val = 6;

print("before: ".print_r($aArray)."<br />");
$aArray = chngNdx($aArray,$ndex,$val);
print("after: ".print_r($aArray)."<br />");
Brook Julias
  • 2,085
  • 9
  • 29
  • 44