PHP 移除阵列(数组)的空白元素

某天突然需要移除阵列(数组)的空白元素,发现以下代码居然没作用:

<?php
foreach($linksArray as $link) {
    if($link == '') {
        unset($link);
    }
}
?>

Stack Overflow
I thought it was worth mentioning that the code above does not work because unset(...) operates on the variable created by the foreach loop, not the original array that obviously stays as it was before the loop.
大意是:foreach内的变量为拷贝副本,unset无作用于原本的阵列(数组)。

后来Google发现以下函数:

array array_filter ( array $array [, callable $callback [, int $flag = 0 ]] )

Parameters 

array       必须,传入阵列(数组)参数
callback  可选,回调函数
flag          可选
                0 - 预设值, 传“”给回调函数,作为回调函数的参数。
                     default, pass value as the only argument to callback instead.
​​​​​​​                ARRAY_FILTER_USE_KEY - 传“索引”给回调函数,作为回调函数的参数。
​​​​​​​                                                               pass key as the only argument to callback instead of the value.
​​​​​​​                ARRAY_FILTER_USE_BOTH - 传“”和“索引”给回调函数,作为回调函数的参数。
​​​​​​​                                                                 pass both value and key as arguments to callback instead of the value.

用法1

​<?php
function odd($value) {
	// return whether the input integer is odd
	return ($value & 1);
}

$Array = array(1, 2, 3, 4, 5);

print_r(array_filter($Array, function($value) {
    return ($value & 1);
}));
?>

Output:​
Array ( [0] => 1 [2] => 3 [4] => 5 ) 

用法2

<?php
function odd($value) {
	// return whether the input integer is odd
	return ($value & 1);
}

$Array = array(1, 2, 3, 4, 5);
$ArrayFilter = array_filter($Array, "odd");       //调用名为odd的函数
$ArrayFilterReindex = array_values($ArrayFilter); //重新建立阵列(数组)的索引

print_r($ArrayFilter);
echo '<br>';
print_r($ArrayFilterReindex);
?>
Output:​
Array ( [0] => 1 [2] => 3 [4] => 5 ) 
Array ( [0] => 1 [1] => 3 [2] => 5 )

猜你喜欢

转载自blog.csdn.net/weixin_42557486/article/details/81167189