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

前端 未结 3 566
猫巷女王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:34

    That depends:

    $a1 = array('a' => 1, 'b' => 2, 'c' => 3);
    unset($a1['b']);
    // array('a' => 1, 'c' => 3)
    
    $a2 = array(1, 2, 3);
    unset($a2[1]);
    // array(0 => 1, 2 => 3)
    // note the missing index 1
    
    // solution 1 for numeric arrays
    $a3 = array(1, 2, 3);
    array_splice($a3, 1, 1);
    // array(0 => 1, 1 => 3)
    // index is now continous
    
    // solution 2 for numeric arrays
    $a4 = array(1, 2, 3);
    unset($a4[1]);
    $a4 = array_values($a4);
    // array(0 => 1, 1 => 3)
    // index is now continous
    

    Generally unset() is safe for hashtables (string-indexed arrays), but if you have to rely on continous numeric indexes you'll have to use either array_splice() or a combination of unset() and array_values().

提交回复
热议问题