tags:

views:

60

answers:

5

hi guys,

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?

+2  A: 
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
`array_insert()` is not pre-defined in PHP. You need to create it yourself.
BoltClock
sorry i just realized i had edited the answer.
sushil bharwani
This answer is the function definition of `array_insert()`
lacqui
+1  A: 

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
A: 

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
+1  A: 

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

aib
`$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
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
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
@GZipp: It is if you want to insert an array, object or NULL.
aib
@aib - Absolutely true, and since doing it that way makes the operation safer, I retract that part of my comment.
GZipp
A: 

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