>  기사  >  백엔드 개발  >  PHP에서 정수 전용 배열을 효율적으로 확인하는 방법은 무엇입니까?

PHP에서 정수 전용 배열을 효율적으로 확인하는 방법은 무엇입니까?

Linda Hamilton
Linda Hamilton원래의
2024-10-17 14:00:05369검색

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으로 문의하세요.