How to Remove Array Element and Then Re-Index Arra

2019-01-02 17:14发布

I have some troubles with an array. I have one array that I want to modify like below. I want to remove element (elements) of it by index and then re-index array. Is it possible?

$foo = array(

    'whatever', // [0]
    'foo', // [1]
    'bar' // [2]

);

$foo2 = array(

    'foo', // [0], before [1]
    'bar' // [1], before [2]

);

8条回答
墨雨无痕
2楼-- · 2019-01-02 17:42
unset($foo[0]); // remove item at index 0
$foo2 = array_values($foo); // 'reindex' array
查看更多
看淡一切
3楼-- · 2019-01-02 17:46

Try with:

$foo2 = array_slice($foo, 1);
查看更多
姐姐魅力值爆表
4楼-- · 2019-01-02 17:50

In addition to xzyfer's answer

The function

function custom_unset(&$array=array(), $key=0) {
    if(isset($array[$key])){

        // remove item at index
        unset($array[$key]);

        // 'reindex' array
        $array = array_values($array);

        //alternatively
        //$array = array_merge($array); 

    }
    return $array;
}

Use

$my_array=array(
    0=>'test0', 
    1=>'test1', 
    2=>'test2'
);

custom_unset($my_array, 1);

Result

 array(2) {
    [0]=>
    string(5) "test0"
    [1]=>
    string(5) "test2"
  }
查看更多
路过你的时光
5楼-- · 2019-01-02 17:52

You better use array_shift(). That will return the first element of the array, remove it from the array and re-index the array. All in one efficient method.

查看更多
余生无你
6楼-- · 2019-01-02 17:53
array_splice($array, array_search(array_value,$array),1);
查看更多
泛滥B
7楼-- · 2019-01-02 18:00

If you use array_merge, this will reindex the keys. The manual states:

Values in the input array with numeric keys will be renumbered with incrementing keys starting from zero in the result array.

http://php.net/manual/en/function.array-merge.php

This is where i found the original answer.

http://board.phpbuilder.com/showthread.php?10299961-Reset-index-on-array-after-unset()

查看更多
登录 后发表回答