我有一个PHP数组如下:

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

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

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


当前回答

接受的答案将数组转换为关联数组,因此,如果您希望将其作为与接受的答案的非关联数组,您可能也必须使用array_values。

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

参考资料在这里

其他回答

function array_remove_by_value($array, $value)
{
    return array_values(array_diff($array, array($value)));
}

$array = array(312, 401, 1599, 3);

$newarray = array_remove_by_value($array, 401);

print_r($newarray);

输出

Array ([0] => 312 [1] => 1599 [2] => 3)

我认为最简单的方法是使用带有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)
}
$fields = array_flip($fields);
unset($fields['myvalue']);
$fields = array_flip($fields);

根据您的要求“每个值只能出现一次”,如果您只是想在数组中保持唯一的值,那么array_unique()可能就是您正在寻找的。

输入:

$input = array(4, "4", "3", 4, 3, "3");
$result = array_unique($input);
var_dump($result);

结果:

array(2) {
  [0] => int(4)
  [2] => string(1) "3"
}

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]

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