我有一个PHP数组如下:

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

我想删除包含值$del_val的元素(例如,$del_val=401),但我不知道它的键。这可能会有帮助:每个值只能在那里出现一次。

我正在寻找执行这项任务的最简单的函数。


当前回答

在PHP 7.4中使用箭头函数:

$messages = array_filter($messages, fn ($m) => $m != $del_val);

为了保持它是一个非关联数组,用array_values()来包装它:

$messages = array_values(array_filter($messages, fn ($m) => $m != $del_val));

其他回答

从数组中删除一个元素基本上就是设置一个元素的差异。

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

它很好地泛化了,你可以同时删除任意多的元素,如果你想的话。

免责声明:请注意,我的解决方案产生了一个新的数组副本,同时保持旧的完整,与变异的接受答案形成对比。选一个你需要的。

使用array_search()和unset,尝试以下操作:

if (($key = array_search($del_val, $messages)) !== false) {
    unset($messages[$key]);
}

Array_search()返回它找到的元素的键,可以使用unset()从原始数组中删除该元素。它将在失败时返回FALSE,但在成功时返回FALSE -y值(例如,您的键可能为0),这就是使用严格比较操作符!==的原因。

if()语句将检查array_search()是否返回值,如果返回值,则只执行操作。

这里有一个简单但可以理解的解决方案:

$messagesFiltered = [];
foreach ($messages as $message) {
    if (401 != $message) {
        $messagesFiltered[] = $message;
    }
}
$messages = $messagesFiltered;

PHP 7.4或以上

function delArrValues(array $arr, array $remove) {
    return array_filter($arr, fn($e) => !in_array($e, $remove));
};

如果你有数组as

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

你想从$messages数组中删除3,312, 你会这样做

delArrValues($messages, [3, 312])

它会返回

[401, 1599]

最好的部分是您可以轻松地过滤多个值,即使相同的值出现了多次。

我认为最简单的方法是使用带有foreach循环的函数:

//This functions deletes the elements of an array $original that are equivalent to the value $del_val
//The function works by reference, which means that the actual array used as parameter will be modified.

function delete_value(&$original, $del_val)
{
    //make a copy of the original, to avoid problems of modifying an array that is being currently iterated through
    $copy = $original;
    foreach ($original as $key => $value)
    {
        //for each value evaluate if it is equivalent to the one to be deleted, and if it is capture its key name.
        if($del_val === $value) $del_key[] = $key;
    };
    //If there was a value found, delete all its instances
    if($del_key !== null)
    {
        foreach ($del_key as $dk_i)
        {
            unset($original[$dk_i]);
        };
        //optional reordering of the keys. WARNING: only use it with arrays with numeric indexes!
        /*
        $copy = $original;
        $original = array();
        foreach ($copy as $value) {
            $original[] = $value;
        };
        */
        //the value was found and deleted
        return true;
    };
    //The value was not found, nothing was deleted
    return false;
};

$original = array(0,1,2,3,4,5,6,7,4);
$del_val = 4;
var_dump($original);
delete_value($original, $del_val);
var_dump($original);

输出将是:

array(9) {
  [0]=>
  int(0)
  [1]=>
  int(1)
  [2]=>
  int(2)
  [3]=>
  int(3)
  [4]=>
  int(4)
  [5]=>
  int(5)
  [6]=>
  int(6)
  [7]=>
  int(7)
  [8]=>
  int(4)
}
array(7) {
  [0]=>
  int(0)
  [1]=>
  int(1)
  [2]=>
  int(2)
  [3]=>
  int(3)
  [5]=>
  int(5)
  [6]=>
  int(6)
  [7]=>
  int(7)
}