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>
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>
By utilizing any and is_int, we can concisely express the integer verification logic:
<code class="php">any($array, 'is_int');</code>
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!