>  기사  >  백엔드 개발  >  PHP의 배열이 정수로만 구성되어 있는지 빠르게 확인하는 방법은 무엇입니까?

PHP의 배열이 정수로만 구성되어 있는지 빠르게 확인하는 방법은 무엇입니까?

Mary-Kate Olsen
Mary-Kate Olsen원래의
2024-10-17 13:57:02410검색

How to Quickly Determine if an Array in PHP Consists Exclusively of Integers?

More Concise way to Check for Integer Arrays

Original Question: How to determine if an array contains only integers?

Native PHP Solution:

The array function provides a more concise method to achieve this:

<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 utilizes the array_filter() function to create a new array containing only elements that satisfy the is_int() condition. By comparing the original and filtered arrays, we can determine if the original array contained only integers.

Higher-Order Function Helpers:

To enhance flexibility, consider defining helper functions:

<code class="php">function all($elems, $predicate) {
  return !any($elems, $predicate); // true if all validate
}

function any($elems, $predicate) {
  foreach ($elems as $elem) {
    if (call_user_func($predicate, $elem)) {
      return true; // true if any validate
    }
  }

  return false;
}</code>

Now, you can use these functions for more complex scenarios:

<code class="php">all([1, 2, 3], 'is_int'); // true
any([1, 'a', 'b'], 'is_int'); // true</code>

This solution provides a concise and flexible way to verify integer arrays in PHP, catering to various use cases.

위 내용은 PHP의 배열이 정수로만 구성되어 있는지 빠르게 확인하는 방법은 무엇입니까?의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

성명:
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.