PHP array_find: How to Locate Array Values with Examples

php array find

PHP array_find was released in PHP 8.4 to locate a value inside an array and returns the first match.

Understand the array_find Function in PHP

The array_find function checks values in an array and returns the first match.

The syntax looks like this:

array_find(array $array, callable $callback): mixed
  • $array holds the list of values.
  • $callback runs on each value.
  • It returns the first value that matches.

This function checks values one by one. It stops once it finds a match. You use this function to pick one value that meets a rule.

Here is an example:

$nums = [2, 4, 6, 7, 8];
$result = array_find($nums, fn($n) => $n > 5);
echo $result;

This returns 6 since it is the first value above five.

Use the array_find with Associative Arrays in PHP

You can use array_find with associative arrays. It checks values but keeps keys safe.

For example:

$users = [
    "john" => 25,
    "sara" => 30,
    "mike" => 18
];
$result = array_find($users, fn($age) => $age < 20);
echo $result;

This returns 18 since Mike’s age matches first.

Here is another example:

$products = [
    "pen" => 2,
    "book" => 5,
    "bag" => 15
];
$result = array_find($products, fn($price) => $price > 10);
echo $result;

This returns 15 since it is the first price above ten.

The Difference between array_find and array_filter

The array_find returns the first value that matches, while the array_filter returns all values that match.

Here is a table that shows you the key differences:

FunctionWhat it ReturnsUse Case
array_findFirst value that matchesStop at first valid value
array_filterAll values that matchKeep a full filtered list

Use array_find to get one value. Use array_filter to collect many values.

Examples of the array_find in PHP

Locate the first even number:

$nums = [3, 7, 10, 12, 15];
$result = array_find($nums, fn($n) => $n % 2 === 0);
echo $result;

This example checks each value and stops once it finds the first even number. The output is 10 since it is the first even value in the list.

Find the first user with the admin role:

$users = [
    ["name" => "alex", "role" => "editor"],
    ["name" => "sara", "role" => "admin"],
    ["name" => "john", "role" => "admin"]
];
$result = array_find($users, fn($u) => $u["role"] === "admin");
echo $result["name"];

This example returns sara since her role is the first match for the admin. The function checks the order and picks the first valid user role.

Match the first long word in a list:

$words = ["pen", "book", "dictionary", "bag"];
$result = array_find($words, fn($w) => strlen($w) > 5);
echo $result;

This example checks string length and picks the first match. It prints dictionary since this is the first word with more than five letters.

Detect the first product with a discount above 30%:

$discounts = [
    "pen" => 5,
    "bag" => 20,
    "phone" => 40,
    "tablet" => 25
];
$result = array_find($discounts, fn($d) => $d > 30);
echo $result;

This example looks at values in order and finds the first high discount. It prints 40 since the phone has the first discount above thirty percent.

Wrapping Up

You learned how array_find locates a single value and how it works with associative arrays. You also saw how it differs from array_filter.

Here is a quick recap:

  • array_find returns the first match.
  • It works with simple and associative arrays.
  • array_filter returns all matches.
  • Use the right function for your case.

FAQs

What does PHP array_find do?

The array_find function searches through an array and returns the first element that matches a condition. Example:
$result = array_find([1, 2, 3, 4], function($n) {
    return $n > 2;
});
echo $result; // Output: 3

How is PHP array_find different from array_filter?

  • array_find returns the first matching value.
  • array_filter returns all matching values.
Example:
$array = [1, 2, 3, 4, 5];

$find = array_find($array, fn($n) => $n > 3);
echo $find; // Output: 4

$filter = array_filter($array, fn($n) => $n > 3);
print_r($filter); // Output: [4, 5]

Can I use PHP array_find with associative arrays?

Yes, array_find works with associative arrays and can locate elements by custom rules. Example:
$users = [
    ["id" => 1, "name" => "Ali"],
    ["id" => 2, "name" => "Sara"],
    ["id" => 3, "name" => "Omar"]
];

$user = array_find($users, function($u) {
    return $u["name"] === "Sara";
});
print_r($user); 
// Output: Array ( [id] => 2 [name] => Sara )

How to write a custom PHP array_find function?

You can create a reusable array_find function that works with any type of array. Example:
function array_find($array, $callback) {
    foreach ($array as $key => $value) {
        if ($callback($value, $key)) {
            return $value;
        }
    }
    return null;
}

$numbers = [10, 20, 30, 40];
$result = array_find($numbers, fn($n) => $n === 30);
echo $result; // Output: 30

Similar Reads

PHP Hello World: Write Your First Program with Code Example

You always start with “Hello World” when you learn a new language. It keeps things simple. You see right away…

PHP Variable Basics: Everything You Need to Know

Think about the PHP variable as little storage boxes holding your data, whether it is a number, a word, or…

PHP Global Variables & Superglobals: A Complete Guide

Variables in PHP are general elements used for data storage and other manipulations. Global variables belong to a particular category…

Install PHP on Operating System: Ubuntu, Windows, and macOS

In this tutorial, you will learn how to install PHP on your Operating system such as Ubuntu, Windows, or macOS.…

Mastering PHP’s Do-While Loop: Examples and Explanation

The PHP do-while loop is a type of loop that executes a block of code at least once, and then…

PHP XML Parsers: Everything You Need to Know

In PHP, manipulation of XML data can be very critical when most systems' data exchange relies on the format. XML—Extensible…

PHP array_fill_keys: Create Arrays with Specific Keys

The PHP array_fill_keys function helps you to build an array where each key has the same value. What is the…

PHP array_any: How it Works with Arrays with Examples

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

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,…

How to Install PHP on a Raspberry Pi

You can use your Raspberry Pi as a personal web server or tool that runs in your home. You do…

Previous Article

HTML bdo Tag – Control Text Direction

Next Article

HTML sup Tag: How to Add Superscript in Web Pages

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.