PHP の配列が整数のみで構成されているかどうかをすばやく判断するにはどうすればよいですか?

Mary-Kate Olsen
リリース: 2024-10-17 13:57:02
オリジナル
407 人が閲覧しました

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 中国語 Web サイトの他の関連記事を参照してください。

ソース:php
このウェブサイトの声明
この記事の内容はネチズンが自主的に寄稿したものであり、著作権は原著者に帰属します。このサイトは、それに相当する法的責任を負いません。盗作または侵害の疑いのあるコンテンツを見つけた場合は、admin@php.cn までご連絡ください。
著者別の最新記事
人気のチュートリアル
詳細>
最新のダウンロード
詳細>
ウェブエフェクト
公式サイト
サイト素材
フロントエンドテンプレート
私たちについて 免責事項 Sitemap
PHP中国語ウェブサイト:福祉オンライン PHP トレーニング,PHP 学習者の迅速な成長を支援します!