To pull the first one from the array, or return false:

current(array_filter($myArray, function($element) { ... }))

More info on current() here.

Answer from Izkata on Stack Overflow
🌐
PHP
php.net › manual › en › function.array-find.php
PHP: array_find - Manual
<?php $array = [ 'a' => 'dog', ... first animal with a name longer than 4 characters. var_dump(array_find($array, function (string $value) { return strlen($value) > 4; })); // Find the first animal whose name begins with ...
🌐
PHP
wiki.php.net › rfc › array_find
PHP: rfc:array_find
If this function returns true, the key is returned from array_find_key and the callback will not be called for further elements. The function returns the key of the first element for which the $callback returns true. If no matching element is found the function returns NULL. $array = [ 'a' => 'dog', 'b' => 'cat', 'c' => 'cow', 'd' => 'duck', 'e' => 'goose', 'f' => 'elephant' ]; // Find the first animal with a name longer than 4 characters.
Top answer
1 of 7
77

To pull the first one from the array, or return false:

current(array_filter($myArray, function($element) { ... }))

More info on current() here.

2 of 7
69

Here's a basic solution

function array_find(f) {
  foreach (x) {
    if (call_user_func(x) === true)
      return $x;
  }
  return null;
}

array_find([1,2,3,4,5,6], function($x) { return $x > 4; });  // 5
array_find([1,2,3,4,5,6], function($x) { return $x > 10; }); // null

In the event x) returns true, the loop short circuits and $x is immediately returned. Compared to array_filter, this is better for our use case because array_find does not have to continue iterating after the first positive match has been found.

In the event the callback never returns true, a value of null is returned.


Note, I used call_user_func(x) instead of just calling x). This is appropriate here because it allows you to use any compatible callable

Class Foo {
  static private $data = 'z';
  static public function match($x) {
    return $x === self::$data;
  }
}

array_find(['x', 'y', 'z', 1, 2, 3], ['Foo', 'match']); // 'z'

Of course it works for more complex data structures too

$data = [
  (object) ['id' => 1, 'value' => 'x'],
  (object) ['id' => 2, 'value' => 'y'],
  (object) ['id' => 3, 'value' => 'z']
];

array_find($data, function($x) { return $x->id === 3; });
// stdClass Object (
//     [id] => 3
//     [value] => z
// )

If you're using PHP 7, add some type hints

function array_find(array $xs, callable $f) { ...

If your array may contain null elements, array_find cannot return null to signal no element was not found. As @dossy suggests, you could use an array result containing either one or zero elements -

function array_find(f) {
  foreach (x) {
    if (call_user_func(x) === true)
      return [$x]; // result
  }
  return []; // not found
}

array_find([1,2,3,4,5,6], function($x) { return $x > 4; });  // [5]
array_find([1,2,3,4,5,6], function($x) { return $x > 10; }); // []
People also ask

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
🌐
flatcoding.com
flatcoding.com › home › php array_find: how to locate array values with examples
PHP array_find: How to Locate Array Values with Examples - FlatCoding
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]
🌐
flatcoding.com
flatcoding.com › home › php array_find: how to locate array values with examples
PHP array_find: How to Locate Array Values with Examples - FlatCoding
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
🌐
flatcoding.com
flatcoding.com › home › php array_find: how to locate array values with examples
PHP array_find: How to Locate Array Values with Examples - FlatCoding
🌐
GitHub
github.com › PHP-Polyfills › array-find
GitHub - PHP-Polyfills/array-find: PHP: Provides a user-land polyfill for `array_find`, `array_find_key`, `array_any` and `array_all` functions added in PHP 8.4. · GitHub
Provides user-land PHP polyfills for the array_find, array_find_key, array_any and array_all functions added in PHP 8.4. Requires PHP 7.1 or later.
Author   PHP-Polyfills
🌐
FlatCoding
flatcoding.com › home › php array_find: how to locate array values with examples
PHP array_find: How to Locate Array Values with Examples - FlatCoding
August 27, 2025 - PHP array_find is a simple way to locate array values. Click here to see examples and learn syntax with clear steps.
🌐
PHP.Watch
php.watch › versions › 8.4 › array_find-array_find_key-array_any-array_all
New `array_find`, `array_find_key`, `array_any`, and `array_all` functions - PHP 8.4 • PHP.Watch
If * this function returns TRUE, the key ($key) is returned * immediately and the callback will not be called for further * elements. * * @return mixed The key of the first element for which the * $callback returns TRUE. NULL, If no matching element is found. */ function array_find_key(array $array, callable $callback): mixed {}
🌐
Stitcher
stitcher.io › blog › array-find-in-php-84
array_find in PHP 8.4 | Stitcher.io
The decision for array_find() over array_first() isn't all that weird though: lots of languages implement a method to find the first matching element from an array, and those functions are always called find.
🌐
ZetCode
zetcode.com › php-array › array-find
PHP array_find - Array Search in PHP
<?php declare(strict_types=1); function array_find(array $array, callable $callback): mixed { foreach ($array as $element) { if ($callback($element)) { return $element; } } return null; } $numbers = [1, 3, 4, 7, 8]; $firstEven = array_find($numbers, fn($n): bool => $n % 2 === 0); echo $firstEven ??
Find elsewhere
🌐
GitHub
gist.github.com › kellenmace › 0395d57978db18d5495f11fead184fa7
array_find() function for PHP · GitHub
$names = [ 'Jerry', 'Newman' ]; $newmans_name = array_find( $names, fn( $name ) => $name === 'Newman' ); echo $newmans_name; // "Newman"
🌐
PHP.Watch
php.watch › codex › array_find
array_find Function • PHP.Watch
PHP 7 · PHP 8.0-8.1 · PHP 8.2-8.3 · PHP 8.4 · Added · PHP 8.5 · PHP 8.6 · array_find(array $array, callable $callback): mixed · Typearray · Typecallable · The callback function to call to check each element, which must be · If this function returns `true`, the value is returned from [`array_find`](/codex/array_find) and the callback will not be called for further elements.
🌐
Reddit
reddit.com › r/php › array_find in php 8.4
r/PHP on Reddit: array_find in PHP 8.4
July 18, 2024 - Still those prehistorical functions... You should be able to do $array->find(); ... For real. I found this quite a few years ago and been wanting support for it built in PHP for years.
Top answer
1 of 12
54

For the canonical reference:

$obj = array_column($array, null, 'id')['one'] ?? false;

The false is per the question's requirement to return false. It represents the nonmatching value, e.g., you can make it null for example as an alternative suggestion.

This works transparently since PHP 7.0. In case you (still) have an older version, there are user-space implementations of it that can be used as a drop-in replacement.

However array_column also means to copy a whole array. This might not be wanted.

Instead it could be used to index the array and then map over with array_flip:

$index = array_column($array, 'id');
$map = array_flip($index);
$obj = $array[$map['one'] ?? null] ?? false;

On the index, the search problem might still be the same. The map just offers the index in the original array, so there is a reference system.

Keep in mind though that this might not be necessary as PHP has copy-on-write. So there might be less duplication as intentionally thought. So this is to show some options.


Another option is to go through the whole array and unless the object is already found, check for a match. One way to do this is with array_reduce:

$obj = array_reduce($array, static function ($carry, $item) {
    return $carry === false && $item->id === 'one' ? $item : $carry;
}, false);

This variant again is with the returning false requirement for no-match.

It is a bit more straight forward with null:

$obj = array_reduce($array, static function ($carry, $item) {
    return $carry ?? ($item->id === 'one' ? $item : $carry);
}, null);

And a different no-match requirement can then be added with $obj = ...) ?? false; for example.

Fully exposing to foreach within a function of its own even has the benefit to directly exit on match:

$result = null;
foreach ($array as $object) {
    if ($object->id === 'one') {
        $result = $object;
        break;
    }
}
unset($object);
$obj = $result ?? false;

This is effectively the original answer by hsz, which shows how universally it can be applied.

2 of 12
40

You can iterate that objects:

function findObjectById($id){
    $array = array( /* your array of objects */ );

    foreach ( $array as $element ) {
        if ( $id == $element->id ) {
            return $element;
        }
    }

    return false;
}

Faster way is to have an array with keys equals to objects' ids (if unique);

Then you can build your function as follow:

function findObjectById($id){
    $array = array( /* your array of objects with ids as keys */ );

    if ( isset( $array[$id] ) ) {
        return $array[$id];
    }

    return false;
}
🌐
Medium
medium.com › @valerio_27709 › how-to-search-in-a-php-associative-array-fast-tips-5890cdf818e0
How to Search in a PHP Associative Array — Fast tips | by Valerio Barbera | Medium
August 15, 2024 - The array_key_exists() function checks if a specific key exists in an associative array. It returns `true` if the key is found and `false` otherwise. $fruits = [ 'apple' => 'red', 'banana' => 'yellow', ]; if (array_key_exists('banana', $fruits)) ...
Top answer
1 of 10
235

Another poossible solution is based on the array_search() function. You need to use PHP 5.5.0 or higher.

Example

$userdb=Array
(
    0 => Array
        (
            "uid" => '100',
            "name" => 'Sandra Shush',
            "url" => 'urlof100'
        ),

    1 => Array
        (
            "uid" => '5465',
            "name" => 'Stefanie Mcmohn',
            "pic_square" => 'urlof100'
        ),

    2 => Array
        (
            "uid" => '40489',
            "name" => 'Michael',
            "pic_square" => 'urlof40489'
        )
);

$key = array_search(40489, array_column($userdb, 'uid'));

echo ("The key is: ".$key);
//This will output- The key is: 2

Explanation

The function `array_search()` has two arguments. The first one is the value that you want to search. The second is where the function should search. The function `array_column()` gets the values of the elements which key is `'uid'`.

Summary

So you could use it as:
array_search('breville-one-touch-tea-maker-BTM800XL', array_column($products, 'slug'));

or, if you prefer:

// define function
function array_search_multidim($array, $column, $key){
    return (array_search($key, array_column($array, $column)));
}

// use it
array_search_multidim($products, 'slug', 'breville-one-touch-tea-maker-BTM800XL');

The original example(by xfoxawy) can be found on the DOCS.
The array_column() page.


Update

Due to Vael comment I was curious, so I made a simple test to meassure the performance of the method that uses array_search and the method proposed on the accepted answer.

I created an array which contained 1000 arrays, the structure was like this (all data was randomized):

[
      {
            "_id": "57fe684fb22a07039b3f196c",
            "index": 0,
            "guid": "98dd3515-3f1e-4b89-8bb9-103b0d67e613",
            "isActive": true,
            "balance": "$2,372.04",
            "picture": "http://placehold.it/32x32",
            "age": 21,
            "eyeColor": "blue",
            "name": "Green",
            "company": "MIXERS"
      },...
]

I ran the search test 100 times searching for different values for the name field, and then I calculated the mean time in milliseconds. Here you can see an example.

Results were that the method proposed on this answer needed about 2E-7 to find the value, while the accepted answer method needed about 8E-7.

Like I said before both times are pretty aceptable for an application using an array with this size. If the size grows a lot, let's say 1M elements, then this little difference will be increased too.

Update II

I've added a test for the method based in array_walk_recursive which was mentionend on some of the answers here. The result got is the correct one. And if we focus on the performance, its a bit worse than the others examined on the test. In the test, you can see that is about 10 times slower than the method based on array_search. Again, this isn't a very relevant difference for the most of the applications.

Update III

Thanks to @mickmackusa for spotting several limitations on this method:

  • This method will fail on associative keys.
  • This method will only work on indexed subarrays (starting from 0 and have consecutively ascending keys).

Note on Update III

  • not taking performance into account: you can use array_combine with array_keys & array_column to overcome this limitation in a one-liner like:
$product_search_index = 
array_search( 'breville-one-touch-tea-maker-BTM800XL', array_filter( array_combine( array_keys($products), array_column( $products, 'slug' ) ) ) );
2 of 10
176

Very simple:

function myfunction($products, $field, $value)
{
   foreach($products as $key => $product)
   {
      if ( $product[$field] === $value )
         return $key;
   }
   return false;
}
🌐
Reddit
reddit.com › r/php › php: rfc:array_find
r/PHP on Reddit: PHP: rfc:array_find
April 21, 2024 - PHP is already criticized for inconsistent naming and these functions will add to it. I cannot think a better name for it though. array_usearch would allude to both existing function and the u-something convention that denotes a function that uses callback. But I don't like it either... May be a pair array_ufind()/array_ufind_get_key() would do. Edit: or, well, for those familiar with javascript's array.find(), array_find()/array_find_get_key(), though I still maintain that find being a synonym for search woud inevitably create a confusion.