开发者

How to insert an element in any position in php

开发者 https://www.devze.com 2023-01-17 21:20 出处:网络
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);

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?


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;
}


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
)


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


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)
        );    
}


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 />");
0

精彩评论

暂无评论...
验证码 换一张
取 消