Ben*_*Ben 2362 php arrays unset
有没有一种简单的方法可以使用PHP从数组中删除元素,这样foreach ($array)就不再包含该元素了?
我认为设置它null会这样做,但显然它不起作用.
Kon*_*lph 2701
删除数组元素有不同的方法,其中一些对某些特定任务比其他任务更有用.
如果您只想删除一个可以使用的数组元素,\unset()或者可以选择删除\array_splice().
此外,如果您有值并且不知道删除元素的键,您可以使用\array_search()该键来获取密钥.
\unset() 方法请注意,使用\unset()数组键时不会更改/ reindex.如果要重新索引可以使用的键,\array_values()之后\unset()将所有键转换为从0开始的数字枚举键.
码
<?php
$array = [0 => "a", 1 => "b", 2 => "c"];
\unset($array[1]);
//? Key which you want to delete
?>
Run Code Online (Sandbox Code Playgroud)
产量
[
[0] => a
[2] => c
]
Run Code Online (Sandbox Code Playgroud)
\array_splice() 方法如果使用\array_splice()键将自动重新索引,但关联键不会改变,而不是\array_values()将所有键转换为数字键.
还\array_splice()需要偏移,而不是关键!作为第二个参数.
码
<?php
$array = [0 => "a", 1 => "b", 2 => "c"];
\array_splice($array, 1, 1);
//? Offset which you want to delete
?>
Run Code Online (Sandbox Code Playgroud)
产量
[
[0] => a
[1] => c
]
Run Code Online (Sandbox Code Playgroud)
array_splice()与\unset()通过引用获取数组相同,这意味着您不希望将这些函数的返回值分配回数组.
如果要删除多个数组元素并且不想调用\unset()或\array_splice()多次调用,可以使用这些函数,\array_diff()或者\array_diff_key()根据您是否知道要删除的元素的值或键来确定.
\array_diff() 方法如果您知道要删除的数组元素的值,则可以使用\array_diff().和以前一样,\unset()它不会改变/重新索引数组的键.
码
<?php
$array = [0 => "a", 1 => "b", 2 => "c"];
$array = \array_diff($array, ["a", "c"]);
//??????????? Array values which you want to delete
?>
Run Code Online (Sandbox Code Playgroud)
产量
[
[1] => b
]
Run Code Online (Sandbox Code Playgroud)
\array_diff_key() 方法如果您知道要删除的元素的键,则需要使用\array_diff_key().在这里,您必须确保将键作为键传递给第二个参数而不是值.否则,你必须翻转数组\array_flip().而且这里的密钥不会改变/重新索引.
码
<?php
$array = [0 => "a", 1 => "b", 2 => "c"];
$array = \array_diff_key($array, [0 => "xy", "2" => "xy"]);
//? ? Array keys which you want to delete
?>
Run Code Online (Sandbox Code Playgroud)
产量
[
[1] => b
]
Run Code Online (Sandbox Code Playgroud)
此外,如果要使用\unset()或\array_splice()删除具有相同值的多个元素,可以使用它\array_keys()来获取特定值的所有键,然后删除所有元素.
Ste*_*rig 1345
应该注意的是,unset()保持索引不变,这是你在使用字符串索引(数组作为哈希表)时所期望的,但在处理整数索引数组时可能会非常令人惊讶:
$array = array(0, 1, 2, 3);
unset($array[2]);
var_dump($array);
/* array(3) {
[0]=>
int(0)
[1]=>
int(1)
[3]=>
int(3)
} */
$array = array(0, 1, 2, 3);
array_splice($array, 2, 1);
var_dump($array);
/* array(3) {
[0]=>
int(0)
[1]=>
int(1)
[2]=>
int(3)
} */
Run Code Online (Sandbox Code Playgroud)
因此,array_splice()如果您想要归一化整数键,可以使用它.另一个选择是使用array_values()后unset():
$array = array(0, 1, 2, 3);
unset($array[2]);
$array = array_values($array);
var_dump($array);
/* array(3) {
[0]=>
int(0)
[1]=>
int(1)
[2]=>
int(3)
} */
Run Code Online (Sandbox Code Playgroud)
小智 362
// Our initial array
$arr = array("blue", "green", "red", "yellow", "green", "orange", "yellow", "indigo", "red");
print_r($arr);
// Remove the elements who's values are yellow or red
$arr = array_diff($arr, array("yellow", "red"));
print_r($arr);
Run Code Online (Sandbox Code Playgroud)
这是上面代码的输出:
Array
(
[0] => blue
[1] => green
[2] => red
[3] => yellow
[4] => green
[5] => orange
[6] => yellow
[7] => indigo
[8] => red
)
Array
(
[0] => blue
[1] => green
[4] => green
[5] => orange
[7] => indigo
)
Run Code Online (Sandbox Code Playgroud)
现在,array_values()将很好地重新索引数值数组,但它将从数组中删除所有键字符串并用数字替换它们.如果需要保留键名(字符串),或者如果所有键都是数字键重新索引数组,请使用array_merge():
$arr = array_merge(array_diff($arr, array("yellow", "red")));
print_r($arr);
Run Code Online (Sandbox Code Playgroud)
输出
Array
(
[0] => blue
[1] => green
[2] => green
[3] => orange
[4] => indigo
)
Run Code Online (Sandbox Code Playgroud)
lia*_*tor 193
$key = array_search($needle, $array);
if ($key !== false) {
unset($array[$key]);
}
Run Code Online (Sandbox Code Playgroud)
小智 65
如果你有一个数字索引数组,其中所有值都是唯一的(或者它们是非唯一的,但你希望删除特定值的所有实例),你可以简单地使用array_diff()删除匹配的元素,如下所示:
$my_array = array_diff($my_array, array('Value_to_remove'));
Run Code Online (Sandbox Code Playgroud)
例如:
$my_array = array('Andy', 'Bertha', 'Charles', 'Diana');
echo sizeof($my_array) . "\n";
$my_array = array_diff($my_array, array('Charles'));
echo sizeof($my_array);
Run Code Online (Sandbox Code Playgroud)
这显示以下内容:
4
3
Run Code Online (Sandbox Code Playgroud)
在此示例中,删除了值为"Charles"的元素,因为可以通过sizeof()调用验证,该调用报告初始数组的大小为4,删除后的大小为3.
Def*_*Day 60
另外,对于命名元素:
unset($array["elementName"]);
Run Code Online (Sandbox Code Playgroud)
KTA*_*Anj 32
销毁数组的单个元素
unset()
$array1 = array('A', 'B', 'C', 'D', 'E');
unset($array1[2]); // Delete known index(2) value from array
var_dump($array1);
Run Code Online (Sandbox Code Playgroud)
输出将是:
array(4) {
[0]=>
string(1) "A"
[1]=>
string(1) "B"
[3]=>
string(1) "D"
[4]=>
string(1) "E"
}
Run Code Online (Sandbox Code Playgroud)
如果需要重新索引数组:
$array1 = array_values($array1);
var_dump($array1);
Run Code Online (Sandbox Code Playgroud)
然后输出将是:
array(4) {
[0]=>
string(1) "A"
[1]=>
string(1) "B"
[2]=>
string(1) "D"
[3]=>
string(1) "E"
}
Run Code Online (Sandbox Code Playgroud)
从数组末尾弹出元素 - 返回已删除元素的值
mixed array_pop(array &$array)
$stack = array("orange", "banana", "apple", "raspberry");
$last_fruit = array_pop($stack);
print_r($stack);
print_r('Last Fruit:'.$last_fruit); // Last element of the array
Run Code Online (Sandbox Code Playgroud)
输出将是
Array
(
[0] => orange
[1] => banana
[2] => apple
)
Last Fruit: raspberry
Run Code Online (Sandbox Code Playgroud)
从数组中删除第一个元素(红色), - 返回已删除元素的值
mixed array_shift ( array &$array )
$color = array("a" => "red", "b" => "green" , "c" => "blue");
$first_color = array_shift($color);
print_r ($color);
print_r ('First Color: '.$first_color);
Run Code Online (Sandbox Code Playgroud)
输出将是:
Array
(
[b] => green
[c] => blue
)
First Color: red
Run Code Online (Sandbox Code Playgroud)
Sau*_*tel 31
<?php
$stack = ["fruit1", "fruit2", "fruit3", "fruit4"];
$fruit = array_shift($stack);
print_r($stack);
echo $fruit;
?>
Run Code Online (Sandbox Code Playgroud)
输出:
[
[0] => fruit2
[1] => fruit3
[2] => fruit4
]
fruit1
Run Code Online (Sandbox Code Playgroud)
Mug*_*mba 27
为了避免进行搜索,可以使用array_diff:
$array = array(3, 9, 11, 20);
$array = array_diff($array, array(11) ); // removes 11
Run Code Online (Sandbox Code Playgroud)
在这种情况下,不必搜索/使用密钥.
Ahm*_*aki 25
如果指定了索引:
$arr = ['a', 'b', 'c'];
$index = 0;
unset($arr[$index]); // $arr = ['b', 'c']
Run Code Online (Sandbox Code Playgroud)
如果我们有值而不是索引:
$arr = ['a', 'b', 'c'];
// search the value to find index
// Notice! this will only find the first occurrence of value
$index = array_search('a', $arr);
if($index !== false){
unset($arr[$index]); // $arr = ['b', 'c']
}
Run Code Online (Sandbox Code Playgroud)
该if条件是必要的,因为如果index没有找到,unset()会自动删除这是不是我们想要的数组的第一个元素。
spy*_*yle 20
如果您必须删除数组中的多个值,并且该数组中的条目是对象或结构化数据,那么[array_filter][1]最好的选择.将保留那些从回调函数返回true的条目.
$array = [
['x'=>1,'y'=>2,'z'=>3],
['x'=>2,'y'=>4,'z'=>6],
['x'=>3,'y'=>6,'z'=>9]
];
$results = array_filter($array, function($value) {
return $value['x'] > 2;
}); //=> [['x'=>3,'y'=>6,z=>'9']]
Run Code Online (Sandbox Code Playgroud)
Joh*_*ers 20
对于关联数组,请使用unset:
$arr = array('a' => 1, 'b' => 2, 'c' => 3);
unset($arr['b']);
// RESULT: array('a' => 1, 'c' => 3)
Run Code Online (Sandbox Code Playgroud)
对于数字数组,请使用array_splice:
$arr = array(1, 2, 3);
array_splice($arr, 1, 1);
// RESULT: array(0 => 1, 1 => 3)
Run Code Online (Sandbox Code Playgroud)
使用unset数字数组不会产生错误,但它会搞砸你的索引:
$arr = array(1, 2, 3);
unset($arr[1]);
// RESULT: array(0 => 1, 2 => 3)
Run Code Online (Sandbox Code Playgroud)
小智 18
unset() 销毁指定的变量.
unset()函数内部的行为可能会有所不同,具体取决于您尝试销毁的变量类型.
如果unset()全局变量在函数内部,则仅销毁局部变量.调用环境中的变量将保留与之前unset()调用的值相同的值.
<?php
function destroy_foo()
{
global $foo;
unset($foo);
}
$foo = 'bar';
destroy_foo();
echo $foo;
?>
Run Code Online (Sandbox Code Playgroud)
上面代码的答案是吧.
到unset()函数内部的全局变量:
<?php
function foo()
{
unset($GLOBALS['bar']);
}
$bar = "something";
foo();
?>
Run Code Online (Sandbox Code Playgroud)
Sim*_*mon 18
如果需要从关联数组中删除多个元素,可以使用array_diff_key()(此处与array_flip()一起使用):
$my_array = array(
"key1" => "value 1",
"key2" => "value 2",
"key3" => "value 3",
"key4" => "value 4",
"key5" => "value 5",
);
$to_remove = array("key2", "key4");
$result = array_diff_key($my_array, array_flip($to_remove));
print_r($result);
Run Code Online (Sandbox Code Playgroud)
输出:
Array ( [key1] => value 1 [key3] => value 3 [key5] => value 5 )
Run Code Online (Sandbox Code Playgroud)
Gig*_*ili 17
// Remove by value
function removeFromArr($arr, $val)
{
unset($arr[array_search($val, $arr)]);
return array_values($arr);
}
Run Code Online (Sandbox Code Playgroud)
在保持索引顺序的情况下删除数组第一项的两种方法,以及如果您不知道第一项的键名。
// 1 is the index of the first object to get
// NULL to get everything until the end
// true to preserve keys
$array = array_slice($array, 1, null, true);
Run Code Online (Sandbox Code Playgroud)
// Rewinds the array's internal pointer to the first element
// and returns the value of the first array element.
$value = reset($array);
// Returns the index element of the current array position
$key = key($array);
unset($array[$key]);
Run Code Online (Sandbox Code Playgroud)
对于此示例数据:
$array = array(10 => "a", 20 => "b", 30 => "c");
Run Code Online (Sandbox Code Playgroud)
你必须有这样的结果:
array(2) {
[20]=>
string(1) "b"
[30]=>
string(1) "c"
}
Run Code Online (Sandbox Code Playgroud)
如果您不能认为该对象位于该数组中,则需要添加检查:
if(in_array($object,$array)) unset($array[array_search($object,$array)]);
Run Code Online (Sandbox Code Playgroud)
如果您想通过引用该对象来删除数组的特定对象,您可以执行以下操作:
unset($array[array_search($object,$array)]);
Run Code Online (Sandbox Code Playgroud)
例子:
<?php
class Foo
{
public $id;
public $name;
}
$foo1 = new Foo();
$foo1->id = 1;
$foo1->name = 'Name1';
$foo2 = new Foo();
$foo2->id = 2;
$foo2->name = 'Name2';
$foo3 = new Foo();
$foo3->id = 3;
$foo3->name = 'Name3';
$array = array($foo1,$foo2,$foo3);
unset($array[array_search($foo2,$array)]);
echo '<pre>';
var_dump($array);
echo '</pre>';
?>
Run Code Online (Sandbox Code Playgroud)
结果:
array(2) {
[0]=>
object(Foo)#1 (2) {
["id"]=>
int(1)
["name"]=>
string(5) "Name1"
}
[2]=>
object(Foo)#3 (2) {
["id"]=>
int(3)
["name"]=>
string(5) "Name3"
}
}
Run Code Online (Sandbox Code Playgroud)
请注意,如果该对象出现多次,它将仅在第一次出现时被删除!
解决方案:
Run Code Online (Sandbox Code Playgroud)unset($array[3]); unset($array['foo']);
Run Code Online (Sandbox Code Playgroud)unset($array[3], $array[5]); unset($array['foo'], $array['bar']);
Run Code Online (Sandbox Code Playgroud)array_splice($array, $offset, $length);
进一步说明:
使用这些函数将从PHP中删除对这些元素的所有引用.如果要在数组中保留一个键,但是值为空,请将空字符串分配给该元素:
$array[3] = $array['foo'] = '';
Run Code Online (Sandbox Code Playgroud)
除了语法之外,使用unset()和为元素分配'' 之间存在逻辑差异.第一个说,This doesn't exist anymore,而第二个说This still exists, but its value is the empty string.
如果您正在处理数字,分配0可能是更好的选择.因此,如果一家公司停止生产型号XL1000链轮,它将更新其库存:
unset($products['XL1000']);
Run Code Online (Sandbox Code Playgroud)
但是,如果它暂时用尽了XL1000链轮,但计划在本周晚些时候从工厂收到新货,那么这样做会更好:
$products['XL1000'] = 0;
Run Code Online (Sandbox Code Playgroud)
如果取消设置()一个元素,PHP会调整数组,以便循环仍能正常工作.它不会压缩阵列以填补缺失的孔.这就是我们所说的所有数组都是关联的,即使它们看起来是数字的.这是一个例子:
// Create a "numeric" array
$animals = array('ant', 'bee', 'cat', 'dog', 'elk', 'fox');
print $animals[1]; // Prints 'bee'
print $animals[2]; // Prints 'cat'
count($animals); // Returns 6
// unset()
unset($animals[1]); // Removes element $animals[1] = 'bee'
print $animals[1]; // Prints '' and throws an E_NOTICE error
print $animals[2]; // Still prints 'cat'
count($animals); // Returns 5, even though $array[5] is 'fox'
// Add a new element
$animals[ ] = 'gnu'; // Add a new element (not Unix)
print $animals[1]; // Prints '', still empty
print $animals[6]; // Prints 'gnu', this is where 'gnu' ended up
count($animals); // Returns 6
// Assign ''
$animals[2] = ''; // Zero out value
print $animals[2]; // Prints ''
count($animals); // Returns 6, count does not decrease
Run Code Online (Sandbox Code Playgroud)
要将数组压缩为密集填充的数值数组,请使用array_values():
$animals = array_values($animals);
Run Code Online (Sandbox Code Playgroud)
或者,array_splice()自动重新索引数组以避免留下漏洞:
// Create a "numeric" array
$animals = array('ant', 'bee', 'cat', 'dog', 'elk', 'fox');
array_splice($animals, 2, 2);
print_r($animals);
Array
(
[0] => ant
[1] => bee
[2] => elk
[3] => fox
)
Run Code Online (Sandbox Code Playgroud)
如果您将阵列用作队列并希望从队列中删除项目,同时仍允许随机访问,则此选项非常有用.要从数组中安全地删除第一个或最后一个元素,请分别使用array_shift()和array_pop().
小智 7
我只想说我有一个具有变量属性的特定对象(它基本上映射了一个表,而我正在更改表中的列,因此反映表的对象中的属性也会有所不同):
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 {}
}
}
}
Run Code Online (Sandbox Code Playgroud)
完全的目的$fields只是,所以我不必在代码中随处查看它们,我只是看一下类的开头并更改属性列表和$ fields数组内容以反映新的属性.
假设您有以下数组:
Array
(
[user_id] => 193
[storage] => 5
)
Run Code Online (Sandbox Code Playgroud)
要删除storage,请执行:
unset($attributes['storage']);
$attributes = array_filter($attributes);
Run Code Online (Sandbox Code Playgroud)
你得到:
Array
(
[user_id] => 193
)
Run Code Online (Sandbox Code Playgroud)
小智 7
遵循默认功能:
一世)
$Array = array("test1", "test2", "test3", "test3");
unset($Array[2]);
Run Code Online (Sandbox Code Playgroud)
II)
$Array = array("test1", "test2", "test3", "test3");
array_pop($Array);
Run Code Online (Sandbox Code Playgroud)
三)
$Array = array("test1", "test2", "test3", "test3");
array_splice($Array,1,2);
Run Code Online (Sandbox Code Playgroud)
IV)
$Array = array("test1", "test2", "test3", "test3");
array_shift($Array);
Run Code Online (Sandbox Code Playgroud)
小智 6
使用以下代码:
$arr = array('orange', 'banana', 'apple', 'raspberry');
$result = array_pop($arr);
print_r($result);
Run Code Online (Sandbox Code Playgroud)
<?php
$array = array("your array");
$array = array_diff($array, ["element you want to delete"]);
?>
Run Code Online (Sandbox Code Playgroud)
在变量中创建数组,$array然后在“您要删除的元素”中添加“ a”。如果要删除多个项目,则:“ a”,“ b”。
<?php
// If you want to remove a particular array element use this method
$my_array = array("key1"=>"value 1", "key2"=>"value 2", "key3"=>"value 3");
print_r($my_array);
if (array_key_exists("key1", $my_array)) {
unset($my_array['key1']);
print_r($my_array);
}
else {
echo "Key does not exist";
}
?>
<?php
//To remove first array element
$my_array = array("key1"=>"value 1", "key2"=>"value 2", "key3"=>"value 3");
print_r($my_array);
$new_array = array_slice($my_array, 1);
print_r($new_array);
?>
<?php
echo "<br/> ";
// To remove first array element to length
// starts from first and remove two element
$my_array = array("key1"=>"value 1", "key2"=>"value 2", "key3"=>"value 3");
print_r($my_array);
$new_array = array_slice($my_array, 1, 2);
print_r($new_array);
?>
Run Code Online (Sandbox Code Playgroud)
输出量
Array ( [key1] => value 1 [key2] => value 2 [key3] =>
value 3 ) Array ( [key2] => value 2 [key3] => value 3 )
Array ( [key1] => value 1 [key2] => value 2 [key3] => value 3 )
Array ( [key2] => value 2 [key3] => value 3 )
Array ( [key1] => value 1 [key2] => value 2 [key3] => value 3 )
Array ( [key2] => value 2 [key3] => value 3 )
Run Code Online (Sandbox Code Playgroud)
使用如下unset功能:
$a = array(
'salam',
'10',
1
);
unset($a[1]);
print_r($a);
/*
Output:
Array
(
[0] => salam
[2] => 1
)
*/
Run Code Online (Sandbox Code Playgroud)
使用该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
)
*/
Run Code Online (Sandbox Code Playgroud)
虽然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' ]
Run Code Online (Sandbox Code Playgroud)
unset()不接受要移除的键数组,因此下面的代码将失败(这会使得稍微更容易动态地使用unset()).
$array = range(0,5);
$remove = [1,2];
$array = unset( $remove ); // FAILS: "unexpected 'unset'"
print_r($array);
Run Code Online (Sandbox Code Playgroud)
相反,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 ]
Run Code Online (Sandbox Code Playgroud)
还有另一种做法尚未提及.有时,摆脱某些数组键的最简单方法是简单地将$ 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 ];
Run Code Online (Sandbox Code Playgroud)
显然,相同的做法适用于文本字符串:
$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' ]
Run Code Online (Sandbox Code Playgroud)