首页  >  文章  >  后端开发  >  如何在 PHP 中有效验证纯整数数组?

如何在 PHP 中有效验证纯整数数组?

Linda Hamilton
Linda Hamilton原创
2024-10-17 14:00:05367浏览

How to Efficiently Verify Integer-Only Arrays in PHP?

使用 PHP 验证仅整数数组

检查数组是否只包含整数的一种方法是通过手动迭代和 is_int() 函数。然而,更有效的方法是利用本机 PHP 功能:

使用 array_filter()

array_filter() 维护满足指定条件的数组元素。使用 is_int() 作为谓词应用它,直接生成一个过滤数组:

<code class="php">$only_integers = array_filter($only_integers, 'is_int'); // true
$letters_and_numbers = array_filter($letters_and_numbers, 'is_int'); // false</code>

使用可重用辅助函数

可以使用可重用辅助函数来增强此方法:

<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>

通过使用这些辅助函数,可以简化原始代码:

<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中文网其他相关文章!

声明:
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn