One way to check if an array exclusively contains integers is through manual iteration and the is_int() function. However, a more efficient approach utilizes native PHP functionality:
array_filter() maintains elements of an array that meet a specified condition. Applying it with is_int() as the predicate directly yields a filtered array:
<code class="php">$only_integers = array_filter($only_integers, 'is_int'); // true $letters_and_numbers = array_filter($letters_and_numbers, 'is_int'); // false</code>
This approach can be augmented with reusable helper functions:
<code class="php">/** * Verify all elements of an array satisfy a given predicate. * * @param array $elems Array to evaluate * @param callable $predicate Predicate to apply * @return bool TRUE if all elements pass, FALSE otherwise */ function all($elems, $predicate) { foreach ($elems as $elem) { if (!call_user_func($predicate, $elem)) { return false; } } return true; } /** * Verify any element of an array satisfies a given predicate. * * @param array $elems Array to evaluate * @param callable $predicate Predicate to apply * @return bool TRUE if any element passes, FALSE otherwise */ function any($elems, $predicate) { foreach ($elems as $elem) { if (call_user_func($predicate, $elem)) { return true; } } return false; }</code>
By employing these helper functions, the original code can be simplified:
<code class="php">$has_only_ints = all($only_integers, 'is_int'); // true $has_only_ints = all($letters_and_numbers, 'is_int'); // false</code>
以上是如何在 PHP 中有效驗證純整數數組?的詳細內容。更多資訊請關注PHP中文網其他相關文章!