如何快速判斷PHP中的陣列是否只由整數組成?

Mary-Kate Olsen
發布: 2024-10-17 13:57:02
原創
406 人瀏覽過

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中文網其他相關文章!

來源:php
本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
作者最新文章
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板
關於我們 免責聲明 Sitemap
PHP中文網:公益線上PHP培訓,幫助PHP學習者快速成長!