How to add an array value to the middle of an array?

前端 未结 4 1184
無奈伤痛
無奈伤痛 2020-12-17 09:06

Lets say I have this array:

$array = array(1,2,\'b\',\'c\',5,6,7,8,9.10);

Later in the script, I want to add the value \'d\' before \'c\'.

相关标签:
4条回答
  • 2020-12-17 09:42

    Use array_splice as following:

    array_splice($array, 3, 0, array('d'));
    
    0 讨论(0)
  • 2020-12-17 09:48

    The Complex answer on Citizen's question is:

    $array = array('Hello', 'world!', 'How', 'are', 'You', 'Buddy?');
    $element = '-- inserted --';
    if (count($array) == 1)
    {
        return $string;
    }
    $middle = ceil(count($array) / 2);
    array_splice($array, $middle, 0, $element);
    

    Will output:

    Array
    (
        [0] => Hello
        [1] => world!
        [2] => How
        [3] => -- inserted --
        [4] => are
        [5] => You
        [6] => Buddy?
    )
    

    So thats what he want.

    0 讨论(0)
  • 2020-12-17 09:57

    See array_splice

    0 讨论(0)
  • 2020-12-17 10:03

    or a more self-made approach: Loop array until you see 'd' insert 'c' then 'd' in the next one. Shift all other entries right by one

    0 讨论(0)
提交回复
热议问题