我想从数组中取消一个已知值的设置。我可以使用for
循环迭代以查找一致的值,然后取消设置。
<?php
for($i=0, $length=count($array); $i<$length; $i++)
{
if( $array[$i] === $valueToUnset )
//unset the value from the array
}
任何想法?有没有办法不用循环就能实现呢?
我假设您的意图是获得索引,因为您已经有了值。我进一步假设还有一种可能性,即所述值将不在数组中,我们必须考虑到这一点。我不确定你在用array_slice做什么。因此,如果我正确理解了您的要求,一个简单的解决方案如下:
<?php
$foundIndex = false; //Initialize variable that will hold index value
$foundIndex = array_search($valueToExtract, $array);
if($foundIndex === null) {
//Value was not found in the array
} else {
unset($array[$foundIndex]; //Unset the target element
}
?>
array_diff
是解决方案:
<?php
array_diff($array, array($valueToUnset));
不需要迭代