有没有一种简单的方法可以使用PHP从数组中删除元素,从而foreach($array)不再包含该元素?
我以为将其设置为null就可以了,但显然它不起作用。
有没有一种简单的方法可以使用PHP从数组中删除元素,从而foreach($array)不再包含该元素?
我以为将其设置为null就可以了,但显然它不起作用。
当前回答
// Remove by value
function removeFromArr($arr, $val)
{
unset($arr[array_search($val, $arr)]);
return array_values($arr);
}
其他回答
unset()数组中的多个碎片元素
虽然这里多次提到unset(),但还需要提到的是,unset(()接受多个变量,从而可以在一次操作中轻松删除数组中的多个非连续元素:
// Delete multiple, noncontiguous elements from an array
$array = [ 'foo', 'bar', 'baz', 'quz' ];
unset( $array[2], $array[3] );
print_r($array);
// Output: [ 'foo', 'bar' ]
动态取消设置()
unset()不接受要删除的键数组,因此下面的代码将失败(但这会使动态使用unset(()稍微容易一些)。
$array = range(0,5);
$remove = [1,2];
$array = unset( $remove ); // FAILS: "unexpected 'unset'"
print_r($array);
相反,unset()可以在foreach循环中动态使用:
$array = range(0,5);
$remove = [1,2];
foreach ($remove as $k=>$v) {
unset($array[$v]);
}
print_r($array);
// Output: [ 0, 3, 4, 5 ]
通过复制数组来删除数组键
还有一种做法尚待提及。有时,消除某些数组键的最简单方法是将$array1复制到$array2中。
$array1 = range(1,10);
foreach ($array1 as $v) {
// Remove all even integers from the array
if( $v % 2 ) {
$array2[] = $v;
}
}
print_r($array2);
// Output: [ 1, 3, 5, 7, 9 ];
显然,同样的做法适用于文本字符串:
$array1 = [ 'foo', '_bar', 'baz' ];
foreach ($array1 as $v) {
// Remove all strings beginning with underscore
if( strpos($v,'_')===false ) {
$array2[] = $v;
}
}
print_r($array2);
// Output: [ 'foo', 'baz' ]
我只想说,我有一个具有可变属性的特定对象(它基本上映射了一个表,我正在更改表中的列,因此反映表的对象中的属性也会发生变化):
class obj {
protected $fields = array('field1','field2');
protected $field1 = array();
protected $field2 = array();
protected loadfields(){}
// This will load the $field1 and $field2 with rows of data for the column they describe
protected function clearFields($num){
foreach($fields as $field) {
unset($this->$field[$num]);
// This did not work the line below worked
unset($this->{$field}[$num]); // You have to resolve $field first using {}
}
}
}
$fields的全部目的只是,所以当代码发生更改时,我不必查看代码中的任何地方,我只需查看类的开头并更改属性列表和$fields数组内容以反映新属性。
使用以下代码:
$arr = array('orange', 'banana', 'apple', 'raspberry');
$result = array_pop($arr);
print_r($result);
遵循默认功能:
PHP:未设置
unset()销毁指定的变量。有关更多信息,请参阅PHP unset
$Array = array("test1", "test2", "test3", "test3");
unset($Array[2]);
PHP:array_pop
函数的作用是删除数组的最后一个元素。有关更多信息,请参阅PHP array_pop
$Array = array("test1", "test2", "test3", "test3");
array_pop($Array);
PHP:array_splice
函数的作用是从数组中删除选定的元素,并用新的元素替换它。有关更多信息,请参阅PHP array_spling
$Array = array("test1", "test2", "test3", "test3");
array_splice($Array,1,2);
PHP:array_shift
函数的作用是从数组中删除第一个元素。有关更多信息,请参阅PHP array_shift
$Array = array("test1", "test2", "test3", "test3");
array_shift($Array);
基于键删除数组元素:
使用unset函数,如下所示:
$a = array(
'salam',
'10',
1
);
unset($a[1]);
print_r($a);
/*
Output:
Array
(
[0] => salam
[2] => 1
)
*/
根据值删除数组元素:
使用array_search函数获取一个元素键,并使用上面的方法删除一个数组元素,如下所示:
$a = array(
'salam',
'10',
1
);
$key = array_search(10, $a);
if ($key !== false) {
unset($a[$key]);
}
print_r($a);
/*
Output:
Array
(
[0] => salam
[2] => 1
)
*/