我们不要急于回答“就这样做”。这是您尝试过的:
代码:(Demo)
$array=[0=>'',1=>'type',3=>'gear',4=>' ',5=>'rarity'];
foreach($array as $key=>$value){
if ($value == ' ' || $value=='' || $value==' ' || empty($value)) { unset($array[$key]); }
echo 'key:'.$key.' value:'.$value."\n";
}
foreach($array as $key=>$value){
if ($value == ' ' || $value=='' || $value==' ' || empty($value)) { unset($array[$key]); }
echo 'key:'.$key.' value:'.$value."\n";
}
它正在做你要求它做的事情。第一个循环取消设置不需要的元素并打印分配给$array 的“副本”的键和值foreach()“写入”和迭代。第二个循环写入并迭代 $array 的新“副本”(之前已被第一个循环修改),您可以看到 empty-ish 元素现在消失了。
输出:
key:0 value: # unset $array[$key] and display $value (these are different entities
key:1 value:type
key:3 value:gear
key:4 value:
key:5 value:rarity
key:1 value:type # you see elements [0] and [4] are removed as intended
key:3 value:gear
key:5 value:rarity
现在,对于“执行此操作”部分...您有多种选择。以下是一些:
代码:(Demo)
$array=[0=>'',1=>'type',3=>'gear',4=>' ',5=>'rarity'];
var_export(array_filter($array,function($v){return strlen(trim($v));})); // professional grade: uses the function specifically designed to perform this function and the process will be instantly understood by future devs that read your code
var_export(preg_grep('/\S/',$array)); // A regular expression filter. Regex solutions should only be used when other methods will not suffice. For this reason, this method is ill-advised
var_export(preg_grep('/^\s*$/',$array,PREG_GREP_INVERT)); // A regular expression filter (inverted pattern filteration). Regex solutions should only be used when other methods will not suffice. For this reason, this method is ill-advised
foreach($array as $k=>$v){ // possibly the fastest method, I didn't test, but it is also the most verbose and less descriptive as a technique
if(!strlen(trim($v))){unset($array[$k]);}
}
var_export($array);
输出:
array (
1 => 'type',
3 => 'gear',
5 => 'rarity',
)array (
1 => 'type',
3 => 'gear',
5 => 'rarity',
)array (
1 => 'type',
3 => 'gear',
5 => 'rarity',
)array (
1 => 'type',
3 => 'gear',
5 => 'rarity',
)
现在最重要的一条建议来自the manual:
如果 var 存在并且具有非空、非零值,则返回 FALSE。
否则返回 TRUE。
以下的东西被认为是空的:
- “”(空字符串)
- 0(0为整数)
- 0.0(0 作为浮点数)
- “0”(0作为字符串)
- 空
- 错误
- 数组()
- (一个空数组)
- $var; (声明的变量,但没有值)
empty() 和 array_filter() 使用了这种“贪婪”默认行为,如果您不知道的话,这真的会给您的任务带来麻烦。这就是为什么在我建议的方法中,我编写了一个自定义过滤条件,并在 foreach 循环中,我将 empty() 替换为 strlen() 调用。