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
🌐
Reddit
reddit.com › r/phphelp › is there a php equivalent of javascript's array.find?
r/PHPhelp on Reddit: Is there a PHP equivalent of Javascript's Array.find?
January 8, 2016 -

array_filter gets you all items that match a given condition, but what I want is to get the first such item

Let's say I want to display a link to a country's capital, given an ID number and a query of the country's cities.

I could do something like

echo $country["Capital"] ?
cityToLink(
	array_filter($cities,
	function($city){
		global $country;
		return $city["ID"] == $country["Capital"];
	}
)[0]):
"N/A"

but that falls apart if the index of the needed city isn't 0, since it seems that array_filter keeps the original indexes intact

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; }); // []
🌐
PHP
php.net › manual › en › function.array-search.php
PHP: array_search - Manual
About searching in multi-dimentional arrays using array_column, to add to the notes from "turabgarip at gmail dot com", here is a workaround to find the correct key: $array_column = 'name'; $searchValue = 'my value ; $result = array_filter($myArray, function ($subarray) use ($array_column, $searchValue) { return isset($subarray[$array_column]) && $subarray[$array_column] === $searchValue; }); echo key($result);
🌐
Fullstackoasis
fullstackoasis.com › articles › 2019 › 12 › 09 › 375
PHP in_array or array_search vs JavaScript includes or indexOf
Now, when researching this topic, I found that PHP has a function that is more appropriate than array_search for my use case. It’s the in_array function. It returns TRUE if the item being sought is found in the input array. That’s really what I wanted!
🌐
Medium
alamriku069.medium.com › php-in-array-vs-array-search-8d0253948cc4
PHP in_array Vs array_search. Assalamualaikum , I am going to explain… | by Alam Riku | Medium
September 10, 2021 - ... Searches for needle in haystack ... case-sensitive manner. ... strict: If the third parameter strict is set to TRUE then the in_array() function will also check the types of the needle in the haystack....
🌐
Stitcher
stitcher.io › blog › array-find-in-php-84
array_find in PHP 8.4 | Stitcher.io
Besides array_find(), there's now also a function called array_find_key().
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;
}
Find elsewhere
🌐
Inspector
inspector.dev › home › how to search in a php associative array – fast tips
How to Search in a PHP Associative Array - inspector.dev
July 1, 2025 - Dozens of executions show that foreach is consistently better than array_map by approximately 10%. But this result can change a lot based on the contextual environment. If you run the snippet in the sandbox linked above you will find out that ...
🌐
W3Schools
w3schools.com › php › func_array_search.asp
PHP array_search() Function
The array_search() function search an array for a value and returns the key. ... If you want to use W3Schools services as an educational institution, team or enterprise, send us an e-mail: sales@w3schools.com · If you want to report an error, or if you want to make a suggestion, send us an e-mail: help@w3schools.com · HTML Tutorial CSS Tutorial JavaScript Tutorial How To Tutorial SQL Tutorial Python Tutorial W3.CSS Tutorial Bootstrap Tutorial PHP Tutorial Java Tutorial C++ Tutorial jQuery Tutorial
🌐
Edureka
edureka.co › blog › array-search-in-php
All you need to know about Array Search in PHP - Edureka
August 14, 2019 - One of the ways to search for a ... inbuilt functions which could be used for searching arrays like array_search, in_array, array_keys, and array_key_exists....
🌐
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.
🌐
DEV Community
dev.to › gbhorwood › php-write-php-84s-arrayfind-from-scratch-5c9m
php: write php 8.4’s array_find from scratch - DEV Community
July 9, 2024 - the only difference between array_find_key and array_find is that the one that is called ‘find_key’ finds the key, not the value.
🌐
PHP
wiki.php.net › rfc › array_find
PHP: rfc:array_find
This RFC proposes the addition of new array functions: array_find, array_find_key, array_any and array_all, which are helper functions for common patterns of checking an array for the existence of elements matching a specific condition.
🌐
WMTips
wmtips.com › php › fastest-function-check-if-value-exists-in-array
The Fastest PHP Function to Check if a Value Exists in an Array. isset vs array_search vs in_array vs other methods - Webmaster Tips
January 25, 2023 - In this article, we are going to find out the fastest PHP function that is used to check if an array contains a value. We will test and compare the performance of five different methods. We will analyze how the parameter $strict affects the performance of array_search and in_array.
🌐
GeeksforGeeks
geeksforgeeks.org › php › search-an-item-in-an-array-in-php
Search an Item in an Array in PHP - GeeksforGeeks
July 23, 2025 - Example: The example shows the use of array_search() function. ... <?php $arr = array(10, 20, 30, 40, 50); $item = 30; $key = array_search($item, $arr); if ($key !== false) { echo "$item exist in array."; } else { echo "$item not exist in array."; } ?>
🌐
Laravel News
laravel-news.com › home › new array find functions in php 8.4
New Array Find Functions in PHP 8.4 - Laravel News
June 3, 2024 - Like array_find(), it returns null if no matching element is found: ... Using Laravel's Collection, you can get functionality similar to the search() method in combination with a closure.
🌐
Libhunt
php.libhunt.com › php-array-alternatives
Array helper Alternatives - PHP Data Structure and Storage | LibHunt
DISCONTINUED. You can find some alternatives below. ... Simple & secure helper to manipulate arrays in various ways, especially for multidimensional arrays Forget about checking for existing keys and E_NOTICE