What is the best way to delete array item in PHP?

前端 未结 3 568
猫巷女王i
猫巷女王i 2021-02-07 20:22

Could you tell me your way to delete an item from array? Do you think it\'s good?

3条回答
  •  独厮守ぢ
    2021-02-07 20:31

    It depends. If want to remove an element without causing gaps in the indexes, you need to use array_splice:

    $a = array('a','b','c', 'd');
    array_splice($a, 2, 1);
    var_dump($a);
    

    Output:

    array(3) {
      [0]=>
      string(1) "a"
      [1]=>
      string(1) "b"
      [2]=>
      string(1) "d"
    }
    

    Using unset can work, but this results in a non-continuous index. This can sometimes be a problem when you iterate over the array using count($a) - 1 as a measure of the upper bound:

    $a = array('a','b','c', 'd');
    unset($a[2]);
    var_dump($a);
    

    Output:

    array(3) {
      [0]=>
      string(1) "a"
      [1]=>
      string(1) "b"
      [3]=>
      string(1) "d"
    }
    

    As you see, count is now 3 but the index of the last element is also 3.

    My recommendation is therefore to use array_splice for arrays with numerical indexes, and use unset only for arrays (dictionaries really) with non-numerical indexes.

提交回复
热议问题