Home > Backend Development > PHP Tutorial > How Can I Swiftly Verify Array Integer Composition Using Native PHP Functions?

How Can I Swiftly Verify Array Integer Composition Using Native PHP Functions?

DDD
Release: 2024-10-17 13:52:02
Original
641 people have browsed it

How Can I Swiftly Verify Array Integer Composition Using Native PHP Functions?

Optimizing Array Integer Verification with Native PHP Functions

Verifying that an array contains only integers is a common task. While iterating through the array and examining each element's type can be a straightforward approach, PHP provides more concise alternatives.

One such solution utilizes the array_filter function, which takes an array and an evaluation function as arguments. In our case, we pass is_int as the evaluation function. If all elements of the array return true when passed to is_int, it implies that the array contains only integers. Conversely, if any element returns false, the presence of non-numeric data is confirmed.

<code class="php">$only_integers       === array_filter($only_integers,       'is_int'); // true
$letters_and_numbers === array_filter($letters_and_numbers, 'is_int'); // false</code>
Copy after login

To further streamline this process, we can define two helper functions: all and any. all checks if all elements of an array satisfy a given predicate, while any verifies if any element fulfills the condition.

<code class="php">function all($elems, $predicate) {
  foreach ($elems as $elem) {
    if (!call_user_func($predicate, $elem)) {
      return false;
    }
  }

  return true;
}

function any($elems, $predicate) {
  foreach ($elems as $elem) {
    if (call_user_func($predicate, $elem)) {
      return true;
    }
  }

  return false;
}</code>
Copy after login

By utilizing any and is_int, we can concisely express the integer verification logic:

<code class="php">any($array, 'is_int');</code>
Copy after login

If the result is true, it signifies that the array contains at least one non-integer element; otherwise, it confirms that all elements are integers.

The above is the detailed content of How Can I Swiftly Verify Array Integer Composition Using Native PHP Functions?. For more information, please follow other related articles on the PHP Chinese website!

source:php
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template