Wie kann man Arrays, die nur Ganzzahlen enthalten, in PHP effizient überprüfen?

Linda Hamilton
Freigeben: 2024-10-17 14:00:05
Original
366 Leute haben es durchsucht

How to Efficiently Verify Integer-Only Arrays in PHP?

Verifying Integer-Only Arrays with PHP

One way to check if an array exclusively contains integers is through manual iteration and the is_int() function. However, a more efficient approach utilizes native PHP functionality:

Using array_filter()

array_filter() maintains elements of an array that meet a specified condition. Applying it with is_int() as the predicate directly yields a filtered array:

<code class="php">$only_integers = array_filter($only_integers, 'is_int'); // true
$letters_and_numbers = array_filter($letters_and_numbers, 'is_int'); // false</code>
Nach dem Login kopieren

Employing Reusable Helper Functions

This approach can be augmented with reusable helper functions:

<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>
Nach dem Login kopieren

By employing these helper functions, the original code can be simplified:

<code class="php">$has_only_ints = all($only_integers, 'is_int'); // true
$has_only_ints = all($letters_and_numbers, 'is_int'); // false</code>
Nach dem Login kopieren

Das obige ist der detaillierte Inhalt vonWie kann man Arrays, die nur Ganzzahlen enthalten, in PHP effizient überprüfen?. Für weitere Informationen folgen Sie bitte anderen verwandten Artikeln auf der PHP chinesischen Website!

Quelle:php
Erklärung dieser Website
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
Neueste Artikel des Autors
Beliebte Tutorials
Mehr>
Neueste Downloads
Mehr>
Web-Effekte
Quellcode der Website
Website-Materialien
Frontend-Vorlage
Über uns Haftungsausschluss Sitemap
Chinesische PHP-Website:Online-PHP-Schulung für das Gemeinwohl,Helfen Sie PHP-Lernenden, sich schnell weiterzuentwickeln!