首页  >  文章  >  后端开发  >  如何有效验证 PHP 数组的整数内容?

如何有效验证 PHP 数组的整数内容?

Susan Sarandon
Susan Sarandon原创
2024-10-17 13:53:29256浏览

How to Validate PHP Arrays for Integer Content Effectively?

整数内容的高效数组验证

在 PHP 中,可以通过多种方法来验证数组是否只包含整数。虽然手动迭代和条件检查是一个可行的选择,但存在一种利用本机 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">// Check if all array elements pass the predicate
function all($elems, $predicate) {
  foreach ($elems as $elem) {
    if (!call_user_func($predicate, $elem)) {
      return false;
    }
  }

  return true;
}

// Check if any array element passes the predicate
function any($elems, $predicate) {
  foreach ($elems as $elem) {
    if (call_user_func($predicate, $elem)) {
      return true;
    }
  }

  return false;
}</code>

有了这些帮助器,我们原来的验证就变成了一个简洁的声明性表达式:

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

简化调用

为了进一步简化验证过程,我们可以将助手封装在一个自定义函数中,该函数接受数组并返回布尔标志:

<code class="php">function array_has_only_ints($array) {
  return all($array, 'is_int');
}</code>

此函数提供了一个 con

以上是如何有效验证 PHP 数组的整数内容?的详细内容。更多信息请关注PHP中文网其他相关文章!

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