在 PHP 中从数组中删除元素
有没有一种简单的方法可以使用 PHP 从数组中删除元素,使得 foreach ($array) 不再包含该元素?
我认为将其设置为 null
就可以了,但显然它不起作用。
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
有没有一种简单的方法可以使用 PHP 从数组中删除元素,使得 foreach ($array) 不再包含该元素?
我认为将其设置为 null
就可以了,但显然它不起作用。
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
接受
或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
发布评论
评论(27)
删除数组元素的方法有多种,其中某些方法对于某些特定任务比其他方法更有用。
删除单个数组元素
如果您只想删除一个数组元素,您可以使用 < code>unset() 或者
array_splice()
。按键还是按值?
如果您知道该值但不知道删除该元素的键,您可以使用
array_search()
获取密钥。仅当元素出现次数不超过一次时,此方法才有效,因为
array_search()
仅返回第一次匹配。unset()
表达式注意:当您使用 < code>unset() 数组键不会改变。
如果您想重新索引键,可以使用
array_values()
在unset()
之后,它将所有键转换为从 0 开始的数字枚举键
(该数组仍然是一个列表)。
示例代码:
示例输出:
array_splice()
功能如果您使用
array_splice()
,(整数)键将自动重新索引,但关联(字符串)键不会改变 - 与
unset()
之后的array_values()
相反,这会将所有键转换为数字键。
注意:
array_splice()
需要偏移量,而不是键作为第二个参数; 偏移
= array_flip(array_keys(
数组))[
key]
。示例代码:
示例输出:
array_splice()
,与unset()
相同,通过引用获取数组。 您无需将返回值分配回数组。删除多个数组元素
如果您想删除多个数组元素但又不想删除
要多次调用
unset()
或array_splice()
,您可以使用函数array_diff()
或array_diff_key()
取决于您是否知道要从数组中删除的元素的值或键。array_diff()
函数如果您知道要删除的数组元素的值,则可以使用 array_diff() 。
与之前的
unset()
一样,它不会更改数组的键。示例代码:
示例输出:
array_diff_key()
< /a> 函数如果您知道要删除的元素的键,那么您需要使用
array_diff_key()
。您必须确保将键作为第二个参数中的键而不是值传递。
键不会重新索引。
示例代码:
示例输出:
如果您想使用
unset()
或array_splice()
删除具有相同值的多个元素,您可以使用array_keys()
获取所有密钥对于特定值然后删除所有元素。
array_filter()
函数如果您想要删除数组中具有特定值的所有元素,可以使用 array_filter() 。
示例代码:
示例输出:
There are different ways to delete an array element, where some are more useful for some specific tasks than others.
Deleting a Single Array Element
If you want to delete just one single array element you can use
unset()
and alternativelyarray_splice()
.By key or by value?
If you know the value and don't know the key to delete the element you can use
array_search()
to get the key.This only works if the element doesn't occur more than once, since
array_search()
returns the first hit only.unset()
ExpressionNote: When you use
unset()
the array keys won’t change.If you want to reindex the keys you can use
array_values()
afterunset()
,which will convert all keys to numerically enumerated keys starting from 0
(the array remains a list).
Example Code:
Example Output:
array_splice()
FunctionIf you use
array_splice()
the (integer) keys will automatically be reindex-ed,but the associative (string) keys won't change — as opposed to
array_values()
afterunset()
,which will convert all keys to numerical keys.
Note:
array_splice()
needs the offset, not the key, as the second parameter; offset
= array_flip(array_keys(
array))[
key]
.Example Code:
Example Output:
array_splice()
, same asunset()
, take the array by reference. You don’t assign the return values back to the array.Deleting Multiple Array Elements
If you want to delete multiple array elements and don’t want
to call
unset()
orarray_splice()
multiple times you can use the functionsarray_diff()
orarray_diff_key()
depending on whether you know the values or the keys of the elements to remove from the array.array_diff()
FunctionIf you know the values of the array elements which you want to delete, then you can use
array_diff()
.As before with
unset()
it won’t change the keys of the array.Example Code:
Example Output:
array_diff_key()
FunctionIf you know the keys of the elements which you want to delete, then you want to use
array_diff_key()
.You have to make sure you pass the keys as keys in the second parameter and not as values.
Keys won’t reindex.
Example Code:
Example Output:
If you want to use
unset()
orarray_splice()
to delete multiple elements with the same value you can usearray_keys()
to get all the keys for a specific valueand then delete all elements.
array_filter()
FunctionIf you want to delete all elements with a specific value in the array you can use
array_filter()
.Example Code:
Example Output:
应该注意的是
unset()
将保持索引不变,这就是你的d 期望使用字符串索引(数组作为哈希表),但在处理整数索引数组时可能会非常令人惊讶:所以
array_splice如果您想规范化整数键,可以使用 ()
。 另一种选择是在array_values()
.net/unset" rel="noreferrer">unset()
:It should be noted that
unset()
will keep indexes untouched, which is what you'd expect when using string indexes (array as hashtable), but can be quite surprising when dealing with integer indexed arrays:So
array_splice()
can be used if you'd like to normalize your integer keys. Another option is usingarray_values()
afterunset()
:这是上面代码的输出:
现在, array_values() 将很好地重新索引数字数组,但它将从数组中删除所有键字符串并用数字替换它们。 如果您需要保留键名称(字符串),或者在所有键都是数字的情况下重新索引数组,请使用 array_merge()
:
This is the output from the code above:
Now, array_values() will reindex a numerical array nicely, but it will remove all key strings from the array and replace them with numbers. If you need to preserve the key names (strings), or reindex the array if all keys are numerical, use array_merge():
Outputs
另外,对于命名元素:
Also, for a named element:
如果您有一个数字索引数组,其中所有值都是唯一的(或者它们不是唯一的,但您希望删除特定值的所有实例),则可以简单地使用 array_diff() 删除匹配元素,如下所示:
例如:
显示以下内容:
在此示例中,值为“Charles”的元素被删除,这可以通过 sizeof() 调用进行验证,该调用报告初始数组的大小为 4,删除后为 3。
If you have a numerically indexed array where all values are unique (or they are non-unique but you wish to remove all instances of a particular value), you can simply use array_diff() to remove a matching element, like this:
For example:
This displays the following:
In this example, the element with the value 'Charles' is removed as can be verified by the sizeof() calls that report a size of 4 for the initial array, and 3 after the removal.
销毁数组的单个元素
unset()
输出将为:
如果需要重新索引数组:
则输出将为:
将元素从数组末尾弹出 - 返回被删除元素的值
mixed array_pop(array &$array)
输出将是
从数组中删除第一个元素(红色),-返回被删除元素的值
mixed array_shift ( array &$array )
输出将是:
Destroy a single element of an array
unset()
The output will be:
If you need to re index the array:
Then the output will be:
Pop the element off the end of array - return the value of the removed element
mixed array_pop(array &$array)
The output will be
Remove the first element (red) from an array, - return the value of the removed element
mixed array_shift ( array &$array )
The output will be:
输出:
Output:
如果指定了索引:
如果我们有值而不是索引:
if
条件是必要的因为如果
index
没有找到,unset()
会自动删除数组的第一个元素!!! 这不是我们想要的。
If the index is specified:
If we have value instead of index:
The
if
condition is necessarybecause if
index
is not found,unset()
will automatically deletethe first element of the array!!! which is not what we want.
如果您必须删除数组中的多个值,并且该数组中的条目是对象或结构化数据,
array_filter()< /code>
是你最好的选择。 那些从回调函数返回 true 的条目将被保留。
If you have to delete multiple values in an array and the entries in that array are objects or structured data,
array_filter()
is your best bet. Those entries that return a true from the callback function will be retained.如果需要从关联数组中删除多个元素,可以使用 array_diff_key( ) (此处与 array_flip() 一起使用):
输出:
If you need to remove multiple elements from an associative array, you can use array_diff_key() (here used with array_flip()):
Output:
关联数组
对于关联数组,请使用
unset
:数字数组
对于数字数组,请使用
array_splice
:注意
使用
unset
对于数字数组不会产生错误,但它会弄乱你的索引:Associative arrays
For associative arrays, use
unset
:Numeric arrays
For numeric arrays, use
array_splice
:Note
Using
unset
for numeric arrays will not produce an error, but it will mess up your indexes:unset()
销毁指定的变量。函数内部
unset()
的行为可能会有所不同,具体取决于您尝试销毁的变量类型。如果全局变量在函数内部
unset()
,则只有局部变量会被销毁。 调用环境中的变量将保留与调用 unset() 之前相同的值。上述代码的答案将是bar。
要
unset()
函数内的全局变量:unset()
destroys the specified variables.The behavior of
unset()
inside of a function can vary depending on what type of variable you are attempting to destroy.If a globalized variable is
unset()
inside of a function, only the local variable is destroyed. The variable in the calling environment will retain the same value as beforeunset()
was called.The answer of the above code will be bar.
To
unset()
a global variable inside of a function:解决方案:
进一步说明:
使用这些函数将从 PHP 中删除对这些元素的所有引用。 如果您想在数组中保留一个键,但值为空,请将空字符串分配给该元素:
除了语法之外,使用 unset() 并将 '' 分配给该元素。 第一个表示
This 不再存在,
而第二个表示This 仍然存在,但其值为空字符串。
如果您正在处理数字,请分配 0可能是一个更好的选择。 因此,如果一家公司停止生产 XL1000 型链轮,它将更新其库存:
但是,如果暂时用完 XL1000 链轮,但计划在本周晚些时候从工厂收到新的货物,则更好:
如果您 unset() 一个元素,PHP 会调整数组,以便循环仍然有效正确。 它不会压缩数组来填充缺失的孔。 这就是我们说所有数组都是关联的,即使它们看起来是数字。 下面是一个示例:
要将数组压缩为密集填充的数字数组,请使用 array_values() :
或者,array_splice() 自动重新索引数组以避免留下漏洞:
如果您将数组用作队列并希望从队列中删除项目,同时仍允许随机访问,这非常有用。 要安全地从数组中删除第一个或最后一个元素,请使用 array_shift() 和 array_pop() 分别。
Solutions:
Further explanation:
Using these functions removes all references to these elements from PHP. If you want to keep a key in the array, but with an empty value, assign the empty string to the element:
Besides syntax, there's a logical difference between using unset() and assigning '' to the element. The first says
This doesn't exist anymore,
while the second saysThis still exists, but its value is the empty string.
If you're dealing with numbers, assigning 0 may be a better alternative. So, if a company stopped production of the model XL1000 sprocket, it would update its inventory with:
However, if it temporarily ran out of XL1000 sprockets, but was planning to receive a new shipment from the plant later this week, this is better:
If you unset() an element, PHP adjusts the array so that looping still works correctly. It doesn't compact the array to fill in the missing holes. This is what we mean when we say that all arrays are associative, even when they appear to be numeric. Here's an example:
To compact the array into a densely filled numeric array, use array_values():
Alternatively, array_splice() automatically reindexes arrays to avoid leaving holes:
This is useful if you're using the array as a queue and want to remove items from the queue while still allowing random access. To safely remove the first or last element from an array, use array_shift() and array_pop(), respectively.
遵循默认函数:
unset()
销毁指定的变量。 更多信息,您可以参考 PHP 取消设置array_pop()
函数删除数组的最后一个元素。 更多信息可以参考 PHP array_poparray_splice()
函数从数组中删除选定的元素并用新元素替换它。 更多信息,您可以参考 PHP array_splicearray_shift()
函数从数组中删除第一个元素。 更多信息,您可以参考PHP array_shiftFollow the default functions:
unset()
destroys the specified variables. For more info, you can refer to PHP unsetThe
array_pop()
function deletes the last element of an array. For more info, you can refer to PHP array_popThe
array_splice()
function removes selected elements from an array and replaces it with new elements. For more info, you can refer to PHP array_spliceThe
array_shift()
function removes the first element from an array. For more info, you can refer to PHP array_shift我只想说我有一个具有可变属性的特定对象(它基本上是映射一个表,并且我正在更改表中的列,因此反映表的对象中的属性也会有所不同)
:
$fields
的整个目的只是,所以当它们更改时我不必在代码中到处查看,我只需查看类的开头并更改属性列表和$fields 数组内容以反映新属性。I'd just like to say I had a particular object that had variable attributes (it was basically mapping a table and I was changing the columns in the table, so the attributes in the object, reflecting the table would vary as well):
The whole purpose of
$fields
was just, so I don't have to look everywhere in the code when they're changed, I just look at the beginning of the class and change the list of attributes and the $fields array content to reflect the new attributes.删除数组的第一项并保持索引顺序的两种方法以及如果您不知道第一项的键名称的情况。
解决方案 #1
解决方案 #2
对于此示例数据:
您必须得到以下结果:
Two ways for removing the first item of an array with keeping order of the index and also if you don't know the key name of the first item.
Solution #1
Solution #2
For this sample data:
You must have this result:
编辑
如果您不能认为该对象位于该数组中,则需要添加检查:
原始答案
如果您想通过引用该对象来删除数组的特定对象,您可以执行以下操作:
示例:
结果:
请注意,如果该对象出现多次,则只会删除第一次出现的对象!
Edit
If you can't take it as given that the object is in that array you need to add a check:
Original Answer
if you want to remove a specific object of an array by reference of that object you can do following:
Example:
Result:
Note that if the object occures several times it will only be removed the first occurence!
unset() 来自数组的多个碎片元素
虽然这里多次提到了
unset()
,但尚未提及unset()
接受多个变量,这使得它轻松在一次操作中从数组中删除多个不连续的元素:unset() 动态
unset() 不接受要删除的键数组,因此下面的代码将失败(这会使使用 unset() 变得稍微容易一些)虽然是动态的)。
相反,可以在 foreach 循环中动态使用 unset():
通过复制数组来删除数组键
还有另一种尚未提及的做法。
有时,删除某些数组键的最简单方法是将 $array1 复制到 $array2 中。
显然,同样的做法也适用于文本字符串:
unset() multiple, fragmented elements from an array
While
unset()
has been mentioned here several times, it has yet to be mentioned thatunset()
accepts multiple variables making it easy to delete multiple, noncontiguous elements from an array in one operation:unset() dynamically
unset() does not accept an array of keys to remove, so the code below will fail (it would have made it slightly easier to use unset() dynamically though).
Instead, unset() can be used dynamically in a foreach loop:
Remove array keys by copying the array
There is also another practice that has yet to be mentioned.
Sometimes, the simplest way to get rid of certain array keys is to simply copy $array1 into $array2.
Obviously, the same practice applies to text strings:
输出
Output
根据键删除数组元素:
使用
unset
函数,如下所示:根据值删除数组元素:
使用
array_search
函数获取元素键并使用以上方式删除数组元素,如下所示:Remove an array element based on a key:
Use the
unset
function like below:Remove an array element based on value:
Use the
array_search
function to get an element key and use the above manner to remove an array element like below:使用以下代码:
Use the following code:
要从 PHP 数组中删除元素,使其不再包含在
foreach
循环中,您可以使用多种方法。 这是一个简单的方法:方法:使用
unset()
方法:使用
array_splice()
方法:使用
array_diff()
方法:使用
array_filter()
这些方法中的每一种都有其特定的用例和对数组结构的影响,尤其是在键方面。 选择最适合您需要的一种。
有关 PHP 中数组操作的更全面的见解和高级示例,您可能会找到这个文章有帮助。
To remove an element from an array in PHP so it's no longer included in a
foreach
loop, you can use several methods. Here's a straightforward approach:Method: Using
unset()
Method: Using
array_splice()
Method: Using
array_diff()
Method: Using
array_filter()
Each of these methods has its specific use cases and effects on the array structure, especially regarding keys. Choose the one that best suits your need.
For more comprehensive insights and advanced examples on array manipulation in PHP, you might find this article helpful.
我来这里是因为我想看看是否有比使用 unset($arr[$i]) 更优雅的解决方案。 令我失望的是,这些答案要么是错误的,要么没有涵盖所有边缘情况。
这就是 array_diff() 不起作用的原因。 键在数组中是唯一的,而元素并不总是唯一的。
结果...
如果两个元素相同,它们将被删除。 这也适用于 array_search() 和 array_flip()。
我看到了很多关于 array_slice() 和 array_splice() 的答案,但这些函数仅适用于数字数组。 如果这里没有回答我所知道的所有答案,那么这里是一个可行的解决方案。
由于 unset($arr[$i]) 将适用于关联数组和数值数组,这仍然不能回答问题。
该解决方案是将键与可处理数字数组和关联数组的工具进行比较。 我为此使用 array_diff_uassoc() 。 该函数比较回调函数中的键。
结果.....
I came here because I wanted to see if there was a more elegant solution to this problem than using unset($arr[$i]). To my disappointment these answers are either wrong or do not cover every edge case.
Here is why array_diff() does not work. Keys are unique in the array, while elements are not always unique.
Results...
If two elements are the same they will be remove. This also applies for array_search() and array_flip().
I saw a lot of answers with array_slice() and array_splice(), but these functions only work with numeric arrays. All the answers I am aware if here does not answer the question, and so here is a solution that will work.
Since unset($arr[$i]) will work on both associative array and numeric arrays this still does not answer the question.
This solution is to compare the keys and with a tool that will handle both numeric and associative arrays. I use array_diff_uassoc() for this. This function compares the keys in a call back function.
Results.....
删除单个数组元素
如果您只想删除一个数组元素,您可以使用
unset()
或array_splice()
。Deleting a Single Array Element
If you want to delete just one single array element you can use
unset()
and alternativelyarray_splice()
.