Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/php/298.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
通过传递值从php数组中删除项_Php_Arrays - Fatal编程技术网

通过传递值从php数组中删除项

通过传递值从php数组中删除项,php,arrays,Php,Arrays,我有一个像这样的php数组 Array ( [0] => WVSE1P [1] => WVSE1MA [2] => WVSEU1Y [3] => WVSEUP ) 如何通过传递值来删除其中的特定条目 下面是我尝试的代码: $array = $items; //array is items foreach($array as $key => $value) { $val= 'WVSE1P'; //item to remove i

我有一个像这样的php数组

Array
(
    [0] => WVSE1P
    [1] => WVSE1MA
    [2] => WVSEU1Y
    [3] => WVSEUP
)
如何通过传递值来删除其中的特定条目

下面是我尝试的代码:

$array = $items; //array is items

foreach($array as $key => $value) 
{

$val= 'WVSE1P'; //item to remove
if ($value == $val) unset($array[$key]);

}
但是它似乎不起作用。

您可能应该使用而不是unset,以便在取消设置后数组索引能够正确匹配

这个怎么样

$val = 'WVSE1P';
$items = array_splice($items, array_search($val), 1);

在迭代该数组时取消设置数组项有时可能会导致某些意外行为。下面是另一个解决方案:

$flipped = array_flip($array);
unset($flipped['WVSE1P']);
$array = array_flip($flipped);

在这种情况下,这应该有效。只需确保数组中的所有值都是唯一的。

此方法删除指定数组中的任何值,而不进行任何循环:例如:

$array = Array("blue", "orange", "red");

$array = array_diff($array, array("blue")); // blue will be removed

//optionally you can realign the elements:

$array = array_values($array);

你的可能不起作用的原因是因为你将它包含在一个循环中,而这个循环不控制数组对象。

如果他最后执行了array_values(),他将丢失数组中的键。它所做的只是返回数组中的值并按顺序对它们进行索引,但是如果他需要保留这些键呢?似乎
$array=array\u merge($array)
会更好。