Deleting an element from an array in PHP

后端 未结 30 3371
时光说笑
时光说笑 2020-11-21 05:55

Is there an easy way to delete an element from an array using PHP, such that foreach ($array) no longer includes that element?

I thought that setting it

30条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-11-21 06:44

    Associative arrays

    For associative arrays, use unset:

    $arr = array('a' => 1, 'b' => 2, 'c' => 3);
    unset($arr['b']);
    
    // RESULT: array('a' => 1, 'c' => 3)
    

    Numeric arrays

    For numeric arrays, use array_splice:

    $arr = array(1, 2, 3);
    array_splice($arr, 1, 1);
    
    // RESULT: array(0 => 1, 1 => 3)
    

    Note

    Using unset for numeric arrays will not produce an error, but it will mess up your indexes:

    $arr = array(1, 2, 3);
    unset($arr[1]);
    
    // RESULT: array(0 => 1, 2 => 3)
    

提交回复
热议问题