PHP array delete by value (not key)

前端 未结 19 2051
花落未央
花落未央 2020-11-22 15:58

I have a PHP array as follows:

$messages = [312, 401, 1599, 3, ...];

I want to delete the element containing the value $del_val

19条回答
  •  暖寄归人
    2020-11-22 16:20

    Well, deleting an element from array is basically just set difference with one element.

    array_diff( [312, 401, 15, 401, 3], [401] ) // removing 401 returns [312, 15, 3]
    

    It generalizes nicely, you can remove as many elements as you like at the same time, if you want.

    Disclaimer: Note that my solution produces a new copy of the array while keeping the old one intact in contrast to the accepted answer which mutates. Pick the one you need.

提交回复
热议问题