Deleting an element from an array in PHP

后端 未结 30 4018
时光说笑
时光说笑 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条回答
  •  傲寒
    傲寒 (楼主)
    2020-11-21 06:46

    If you have a numerically indexed array where all values are unique (or they are non-unique but you wish to remove all instances of a particular value), you can simply use array_diff() to remove a matching element, like this:

    $my_array = array_diff($my_array, array('Value_to_remove'));
    

    For example:

    $my_array = array('Andy', 'Bertha', 'Charles', 'Diana');
    echo sizeof($my_array) . "\n";
    $my_array = array_diff($my_array, array('Charles'));
    echo sizeof($my_array);
    

    This displays the following:

    4
    3
    

    In this example, the element with the value 'Charles' is removed as can be verified by the sizeof() calls that report a size of 4 for the initial array, and 3 after the removal.

提交回复
热议问题