PHP Unset Array value effect on other indexes

后端 未结 6 1178
春和景丽
春和景丽 2020-12-11 00:17

I am working with a PHP loop, and I had one question regarding how unset affects the array keys. This array uses the standard numeric keys assigned by PHP, 0, 1, 2, 3

6条回答
  •  隐瞒了意图╮
    2020-12-11 01:07

    The keys are maintained with the removed key missing but they can be rearranged by doing this:

    $array = array(1,2,3,4,5);
    unset($array[2]);
    $arranged = array_values($array);
    print_r($arranged);
    

    Outputs:

    Array
    (
        [0] => 1
        [1] => 2
        [2] => 4
        [3] => 5
    )
    

    Notice that if we do the following without rearranging:

    unset($array[2]);
    $array[]=3;
    

    The index of the value 3 will be 5 because it will be pushed to the end of the array and will not try to check or replace missing index. This is important to remember when using FOR LOOP with index access.

提交回复
热议问题