1. 程式人生 > >PHP 移除陣列(陣列)的空白元素

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 )