Heim  >  Artikel  >  Backend-Entwicklung  >  Wie kann man schnell feststellen, ob ein Array in PHP ausschließlich aus ganzen Zahlen besteht?

Wie kann man schnell feststellen, ob ein Array in PHP ausschließlich aus ganzen Zahlen besteht?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-10-17 13:57:02407Durchsuche

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.

Das obige ist der detaillierte Inhalt vonWie kann man schnell feststellen, ob ein Array in PHP ausschließlich aus ganzen Zahlen besteht?. Für weitere Informationen folgen Sie bitte anderen verwandten Artikeln auf der PHP chinesischen Website!

Stellungnahme:
Der Inhalt dieses Artikels wird freiwillig von Internetnutzern beigesteuert und das Urheberrecht liegt beim ursprünglichen Autor. Diese Website übernimmt keine entsprechende rechtliche Verantwortung. Wenn Sie Inhalte finden, bei denen der Verdacht eines Plagiats oder einer Rechtsverletzung besteht, wenden Sie sich bitte an admin@php.cn