How to remove values from an array in PHP?

前端 未结 6 430
终归单人心
终归单人心 2020-12-06 10:03

Is there a PHP function to remove certain array elements from an array?

E.g., I have an array (A) with values and another array (B) from wh

6条回答
  •  南笙
    南笙 (楼主)
    2020-12-06 10:38

    I came accros this post looking for a way to remove one single value from an array (which the title states). Here is a straight forward way, assuming the value to remove is in the array:

    $list = array('foo', 'bar', 'yay', '\o/');
    $toremove = 'foo';
    unset($list[array_search($toremove, $list)]);
    

    Though this will throw errors if the element to remove is not part of the array.

    Another solution, but not really optimised performance wise is:

    $list = array('foo', 'bar', 'yay', '\o/');
    $toremove = 'foo';
    $list = array_flip($list);
    unset($list[$toremove]);
    $list = array_flip($list);
    

    Anyway, perhaps creating an array with the single value as using array_diff as suggested by everyone here is quicker and more efficient.

提交回复
热议问题