Deleting an element from an array in PHP

后端 未结 30 3411
时光说笑
时光说笑 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:28

    If the index is specified:

    $arr = ['a', 'b', 'c'];
    $index = 0;    
    unset($arr[$index]);  // $arr = ['b', 'c']
    

    If the index is NOT specified:

    $arr = ['a', 'b', 'c'];
    $index = array_search('a', $arr); // search the value to find index
    if($index !== false){
       unset($arr[$index]);  // $arr = ['b', 'c']
    }
    

    The if condition is necessary because if index is not found, unset() will automatically delete the first element of the array which is not what we want.

提交回复
热议问题