PHP array_any: How it Works with Arrays with Examples

php array_any

PHP 8.4 released the array_any to test if at least one element matches a condition.

Understand the array_any Function in PHP

The array_any checks elements in an array. It returns true if one element passes the test. It returns false if no element passes the test.

The syntax looks like this:

array_any(array $array, callable $callback)
  • $array: the array you want to check.
  • $callback: the test function that runs on each element.

The function moves through each array element in order. It runs the callback with the element. The function stops when the callback returns true once. The function then returns true. If no element passes, the function returns false.

Here is a quick example:

$numbers = [2, 4, 6, 7];
$result = array_any($numbers, fn($n) => $n % 2 !== 0);
var_dump($result);

This code checks if at least one number is odd. It finds that 7 is odd, so the function returns true.

So, how to implement PHP array_any in your code?

Not all PHP versions have this function. You can write your own function if the function does not exist with this code:

if( !function_exists( 'array_any' ) ) {
  function array_any(array $array, callable $callback): bool {
      foreach ($array as $value) {
          if ($callback($value)) {
              return true;
          }
      }
      return false;
  }
}

This custom code runs the same logic. It checks each element and exits early once a match appears.

The Difference Between array_any and Built-in Functions in PHP

The array_any looks like array_filter or in_array, but the purpose is different. array_any only checks if a condition passes for one element.

Here is a table that shows key differences:

FunctionPurposeReturn Type
array_anyCreate an array with only matching elementsBoolean
array_filterCreate array with only matching elementsArray
in_arrayCheck if value exists in arrayTest if any element passes the condition

Use array_any when you only need a yes or no check. Do not use it to collect results.

Examples of array_any Function in PHP

Check Even Numbers:

$nums = [1, 3, 5, 8];
$result = array_any($nums, fn($n) => $n % 2 === 0);
var_dump($result); // bool(true)

This code tests if the array has at least one even number, and the function finds 8 as even, so it returns true.

Check Strings for a Letter:

$words = ["hat", "dog", "cat"];
$result = array_any($words, fn($w) => strpos($w, "a") !== false);
var_dump($result); // bool(true)

This code checks each string to see if it holds the letter “a”. The function finds “hat” and “cat”, so it returns true.

Validate User Ages:

$ages = [12, 15, 20];
$result = array_any($ages, fn($a) => $a >= 18);
var_dump($result); // bool(true)

This code checks if any user is an adult with age 18 or more. The function finds 20, so it returns true.

Detect Negative Numbers:

$values = [4, -3, 7, 9];
$result = array_any($values, fn($v) => $v < 0);
var_dump($result); // bool(true)

This code scans each number to see if it is negative. The function finds -3, so it returns true.

Wrapping Up

You learned what array_any does and how it behaves with arrays. Here is a quick recap:

  • It checks if any array element passes a condition.
  • It returns true at the first match.
  • It returns false if no element matches.
  • You can build your own function in versions without it.
  • It differs from array_filter and in_array because it only tests and returns a boolean.

FAQs

What is php array_any function?

php array_any is not a built-in function in PHP. It is a custom function that checks if any element in an array meets a given condition.

function array_any($array, $callback) {
    foreach ($array as $value) {
        if ($callback($value)) {
            return true;
        }
    }
    return false;
}

How do I use php array_any with numbers?

You can use php array_any to check conditions on numeric arrays like checking if any value is greater than 10.

$numbers = [3, 7, 15, 2];

$result = array_any($numbers, function($n) {
    return $n > 10;
});

var_dump($result); // true

How does php array_any compare to array_filter?

array_filter returns all values that meet a condition while array_any stops once it finds the first match and returns true or false.

$values = [1, 2, 3, 4];

$any = array_any($values, fn($v) => $v === 3); 
// true

$filter = array_filter($values, fn($v) => $v === 3); 
// [2 => 3]

Can php array_any work with strings?

Yes, php array_any can check string conditions such as length or substring presence.

$words = ["apple", "banana", "pear"];

$result = array_any($words, function($word) {
    return strlen($word) > 5;
});

var_dump($result); // true

Similar Reads

PHP array_count_values: How it Works with Examples

Developers use the array_count_values function in PHP to find how many times each value appears in an array. What is…

PHP For Loop: Run Code Using a Counter with Examples

You may need to repeat tasks in PHP. The PHP for loop solves this by letting you run code many…

PHP Assignment Operators: A Complete Guide

The assignment operators are the sets of gears that keep your code well-oiled and running when deep in PHP, allowing…

PHP Prepared Statements in MySQL: Preventing SQL Injection

MySQL Prepared Statements in PHP are an important tool for ensuring security and optimization. They safeguard against SQL injection attacks,…

Understanding the PHP Enumerable

Actually, the PHP enumerable is a new feature of 8.1 which allows you to define a new type. This feature…

PHP array_change_key_case: Change Array Key Cases

The array_change_key_case function in PHP changes all array keys to lowercase or uppercase for consistent data use. Understand the array_change_key_case…

PHP Syntax: Standard Tags, Echo, and Short Tags

Understanding PHP syntax is like the basics of any language—PHP syntax defines the rules for writing code that a server…

PHP filter_var_array: How to Validate Multiple Inputs

The filter_var_array() appeared to make input validation simple and sanitization in PHP. It handles multiple inputs with different filters was…

PHP array_map Function: How to Transform Arrays with Examples

PHP added the array_map() function to help you apply one function to each item in an array. Understand the array_map…

PHP Comment: How to Write Comments in PHP

let's now dive into PHP comments—these simple but super important integral parts of PHP coding. You can think of comments…

Previous Article

HTML5 New Elements with Examples

Next Article

Understanding Comments in JavaScript for Beginners

Write a Comment

Leave a Comment

Your email address will not be published. Required fields are marked *


Subscribe to Get Updates

Get the latest updates on Coding, Database, and Algorithms straight to your inbox.
No spam. Unsubscribe anytime.