當前位置: 首頁> 最新文章列表> array_filter() 搭配全局函數如is_numeric 使用

array_filter() 搭配全局函數如is_numeric 使用

M66 2025-06-03

在PHP 中, array_filter()是一個非常實用的函數,可以用於對數組中的元素進行篩選,只保留符合條件的元素。它通常與回調函數配合使用,而在很多實際應用中,使用全局函數(如is_numeric )來篩選數據,是一種簡潔而高效的方式。

本文將通過示例來演示如何使用array_filter()搭配is_numeric來篩選數組中的數字元素。

基本語法

array_filter(array $array, ?callable $callback = null, int $mode = 0): array
  • $array :輸入數組。

  • $callback :用於判斷每個元素是否保留的回調函數。

  • $mode :過濾模式,可選。

如果不提供回調函數, array_filter()默認會去除所有等價於false的值(如false0""null等)。

示例:篩選出數組中的數值元素

$items = ['apple', 42, '123', null, 0, 'banana', 3.14, '0', true];

$numericItems = array_filter($items, 'is_numeric');

print_r($numericItems);

輸出結果:

 Array
(
    [1] => 42
    [2] => 123
    [6] => 3.14
    [7] => 0
)

可以看到, array_filter()保留了數組中所有通過is_numeric判斷為數值的元素。這包括整數、浮點數、數字字符串(如'123' )、甚至是字符串'0'

使用匿名函數與其他條件組合

你也可以將is_numeric搭配其他條件使用,例如:

 $items = ['apple', 42, '123', null, 0, 'banana', 3.14, '0', true];

// 只保留大於 10 的數值
$filtered = array_filter($items, function ($item) {
    return is_numeric($item) && $item > 10;
});

print_r($filtered);

輸出結果:

 Array
(
    [1] => 42
    [2] => 123
)

實際應用場景

舉個例子,假設你的網站(如https://m66.net/form-handler.php )接收到一個包含用戶輸入的數據數組,其中可能包含文本、空值或者數字。你希望只提取出數字來進行統計或驗證,這時就可以用array_filter()搭配is_numeric()快速完成這個任務。

小結

  • array_filter()可用於對數組元素進行篩選。

  • 搭配全局函數如is_numeric使用時非常簡潔高效。

  • 可以通過匿名函數進一步組合邏輯進行複雜篩選。

掌握好這一技巧,可以讓你的PHP 代碼在數據處理方面更加靈活和強大。