取消设置空数组元素
我正在使用 $_FILES
,有时由于表单上的文件输入为空,数组具有空数组元素。我正在尝试取消设置这些元素。
我已经尝试过这些代码片段:
foreach($_FILES['images']['name'] as $image)
{
if(empty($image))
{
unset($image);
}
}
foreach($_FILES['images']['name'] as $image)
{
if($image == "")
{
unset($image);
}
}
foreach($_FILES['images']['name'] as $image)
{
if(!$image)
{
unset($image);
}
}
但数组总是返回空元素。实际上是否有一种用 PHP 删除空 $_FILES 数组元素的合理方法?
I'm working with $_FILES
and sometimes the array has empty array elements due to empty file inputs on my form. I'm trying to unset these elements.
I've tried these code snippets:
foreach($_FILES['images']['name'] as $image)
{
if(empty($image))
{
unset($image);
}
}
foreach($_FILES['images']['name'] as $image)
{
if($image == "")
{
unset($image);
}
}
foreach($_FILES['images']['name'] as $image)
{
if(!$image)
{
unset($image);
}
}
But the array always comes back with empty elements. Is there actually a sane way of deleting empty $_FILES array elements with PHP?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
当您使用
foreach($_FILES['images']['name'] as $image)
语句 $image 成为数组中实际元素的副本时,您所做的是取消设置该副本,你应该这样做:When you use
foreach($_FILES['images']['name'] as $image)
statement $image becomes a copy of the actual element in the array, what you are doing is unsetting that copy, this is how you should do it:首先,您的问题并不具体,因为如果您使用单个文件,则不需要 foreach( ($_FILES['images']['name'] as $image)。
您再次提到表单中的空字段,这应该会触发案例 4 错误。那就是没有上传文件。因此,如果您的错误方法设置如下
,则会通知错误,并且您知道已上传空图像。为了减轻 UNSET() 的压力。
如果是多重上传,你会得到类似的东西
to start with, your question is not specific because if u are working with asingle file there is no need of foreach( ($_FILES['images']['name'] as $image).
again u metioned empty fields in your form, this ought to trigger case 4 error. That is no file was uploaded. so with ur error method set like this
With this an error is notified and u know that an empty image as been uploaded. to save urself the stress of UNSET().
if it is multi uploads you will have something like
这个不循环的答案怎么样?
或者,如果您更喜欢一行:
来自
array_filter
:
“如果未提供回调,则所有等于 FALSE 的输入条目(请参阅转换为布尔值)将被删除。”
How about this non-loopy answer?
Or if you prefer one line:
From the manual page for
array_filter
:"If no callback is supplied, all entries of input equal to FALSE (see converting to boolean) will be removed."
除了没有人的回答之外,如果您还想从
type
、tmp_name
、size
等数组中删除元素,请使用:In addition to nobody's answer, if you also want to strip the element from the
type
,tmp_name
,size
etc. arrays use:使用错误代码是最好的
using error code would be best