PHP array_find_key: How it Works with Examples

php array_find_key

The PHP array_find_key function finds a key in an array by a condition. It checks each element and returns the first key that matches.

Understand the array_find_key in PHP

The array_find_key function returns the first key that matches a callback test. It scans each element in order and stops at the first match. This function was released in PHP 8.4.

The syntax looks like this:

array_find_key(array $array, callable $callback)
  • $array is the input array.
  • $callback is the function that checks each value.
  • It returns the matching key or false if no key matches.

The function takes an array and a test. It checks each element. Once the callback returns true, it gives back the key. If no element passes, it returns false.

Here is a quick example:

$arr = ["a" => 2, "b" => 7, "c" => 10];
$key = array_find_key($arr, fn($v) => $v > 5);
echo $key; // b

The function checks each value. It finds 7 at key "b". The result is "b".

This array_find_key runs a test on each value with a callback. It stops once the test returns true. It then gives back the key.

The array_search looks for a direct value in the array. It does not use a test. It compares values and returns the first matching key.

Here are the key differences:

FunctionMethodOutputUse case
array_find_keyUses a callback testFirst key that passes testFlexible checks on values
array_searchDirect value searchFirst key with that valueSimple match by value

Use array_find_key if you need a test like greater than or less than. Use array_search if you need a direct match of a value.

Examples of array_find_key in PHP

Find the first number over a limit:

$nums = [3, 6, 9, 12, 15];
$key = array_find_key($nums, fn($v) => $v > 10);
echo $key; // 3

The function scans the list from left to right. It stops once it finds 12. The output key is 3 since the value 12 sits at that index.

Find the first word that starts with the letter:

$words = ["cat", "dog", "bird", "ant"];
$key = array_find_key($words, fn($v) => $v[0] === "b");
echo $key; //2

The test checks the first letter of each word. It finds "bird" as the first match. The index of "bird" is 2 and that is the result.

Find the first user with an age above 18:

$users = [
   ["name" => "Ali", "age" => 15],
   ["name" => "Sara", "age" => 20],
   ["name" => "Omar", "age" => 25]
];
$key = array_find_key($users, fn($v) => $v["age"] > 18);
echo $key; // 1

The test checks each age in the list. It finds "Sara" since her age is 20. The function then stops and returns the key 1.

Find the first product with a price under the limit:

$products = [
   "apple" => 5,
   "banana" => 8,
   "mango" => 12,
   "grape" => 15
];
$key = array_find_key($products, fn($v) => $v < 10);
echo $key; // apple

The test checks each price in the list. The first match is "apple" with value 5. The function then returns the key "apple".

Wrapping Up

You learned the use of array_find_key and the way it differs from array_search. Here is a quick recap:

  • The array_find_key gives you the ability to run a test with a callback.
  • It returns the first key that passes the test.
  • The array_search looks for a direct value without a test.
  • You can use the array_find_key to check and array_search for direct value matches.

FAQs

What is PHP array_find_key used for?

PHP array_find_key is used to find the key of a given value. It helps when you must match values and return their keys. Example:
$array = ["id" => 101, "name" => "Ali", "age" => 22];
$key = array_search("Ali", $array);
echo $key; // Output: name

How does PHP array_find_key differ from array_search?

array_find_key refers to the concept of finding keys, while array_search is the built-in function that actually performs it.
  • array_search: Returns the first key that matches a value.
  • array_keys: Returns all keys matching a value.
$data = ["red" => 1, "blue" => 2, "green" => 3];
$key = array_search(2, $data);
echo $key; // Output: blue

Can PHP array_find_key work with multidimensional arrays?

Yes, but you must loop through the nested arrays because array_search only works on one level.
$array = [
    "user1" => ["id" => 101, "name" => "Sara"],
    "user2" => ["id" => 102, "name" => "Omar"]
];

foreach ($array as $key => $value) {
    if ($value["name"] === "Omar") {
        echo $key; // Output: user2
    }
}

How to return all keys for a repeated value in PHP?

You can use array_keys instead of array_search because it returns multiple keys at once.
$data = ["x" => 1, "y" => 2, "z" => 1];
$result = array_keys($data, 1);
print_r($result); // Output: Array ( [0] => x [1] => z )

Similar Reads

PHP array_diff_ukey Function: How it Works with Examples

The PHP array_diff_ukey function compares keys in two or more arrays. It returns the keys from the first array that…

PHP strict_types: How the Strict Mode Works

If you want to write good PHP code, strict mode should be on your radar. Strict mode—activated by the command declare(strict_types=1); at…

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…

PHP fopen: Understanding fopen Modes

PHP has great tools to handle external files such as opening, writing, deleting and more else, in this tutorial we…

PHP Spaceship Operator

If you are new to the PHP Spaceship Operator, then let me tell you, you're in for a treat. This…

PHP $_FILES: How to Upload Files in PHP

The PHP superglobal $_FILES is a very important utility and great for dealing with file uploads on the web. When a user…

Parameters and Arguments in PHP: What’s the Difference?

If you're coding in PHP you've most probably come across the terms 'parameters' and 'arguments' in functions. Well, they are…

OOP Interface PHP: How to Set Rules for Classes

PHP developers relied on class inheritance to share functionality before the OOP interface, but this approach had limits. It solves…

Inheritance in PHP: Share Code from Class to Class & Examples

PHP developers copied and pasted code across multiple files before inheritance came, which made updates difficult. They updated functions in…

PHP strlen Function: How It Works with Strings

Developers needed a way to check the length of a string, so the strlen function was introduced to handle this…

Previous Article

Node.js Modules in Depth with Examples

Next Article

JavaScript unshift Function: How it Works with Examples

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.