使用本機 PHP 函數最佳化陣列整數驗證
驗證陣列是否只包含整數是常見任務。雖然迭代數組並檢查每個元素的類型可能是一種簡單的方法,但 PHP 提供了更簡潔的替代方案。
其中一個解決方案利用 array_filter 函數,該函數將陣列和評估函數作為參數。在我們的例子中,我們傳遞 is_int 作為評估函數。如果傳遞給 is_int 時數組的所有元素都傳回 true,則表示該數組僅包含整數。相反,如果任何元素傳回 false,則確認非數字資料的存在。
<code class="php">$only_integers === array_filter($only_integers, 'is_int'); // true $letters_and_numbers === array_filter($letters_and_numbers, 'is_int'); // false</code>
為了進一步簡化這個過程,我們可以定義兩個輔助函數:all 和 any。 all 檢查陣列中的所有元素是否滿足給定的謂詞,而any 則驗證是否有任何元素滿足條件。
<code class="php">function all($elems, $predicate) { foreach ($elems as $elem) { if (!call_user_func($predicate, $elem)) { return false; } } return true; } function any($elems, $predicate) { foreach ($elems as $elem) { if (call_user_func($predicate, $elem)) { return true; } } return false; }</code>
利用any 和is_int,我們可以簡潔地表達整數驗證邏輯:
<code class="php">any($array, 'is_int');</code>
如果結果為true,則表示數組中至少包含一個非整數元素;否則,它確認所有元素都是整數。
以上是如何使用 PHP 原生函數快速驗證數組整數組成?的詳細內容。更多資訊請關注PHP中文網其他相關文章!