dragon8899 2010-05-11 16:09
浏览 70
已采纳

从数组中删除元素(PHP)

I want to remove an element from a PHP array (and shrink the array size). Just looking at the PHP docs, it seems this can be done using array_slice() and array_merge()

so I am guessing (off the top of my head) that some combination of array_merge() and array_slice will work. However, array_slice() requires an index (not a key), so I'm not sure how to quickly cobble these functions together for a solution.

Has anyone implemented such a function before?. I'm sure it must be only a few lines long, but I cant somehow get my head around it (its been one of those days) ...

Actually, I just came up with this cheesy hack when writing up this question....

function remove_from_array(array $in, value) {
   return array_diff($in, (array)$value);
}

too ugly? or will it work (without any shocking side effects)?

  • 写回答

6条回答 默认 最新

  • dongqiao1888 2010-05-11 16:13
    关注

    This functionality already exists; take a look at unset.

    http://php.net/manual/en/function.unset.php

    
    $a = array('foo' => 'bar', 'bar' => 'gork');
    unset($a['bar']);
    print_r($a);
    
    

    output will be:

    array(
    [foo] => bar
    )
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(5条)

报告相同问题?