function searchForId($id, $array) {
   foreach ($array as $key => $val) {
       if ($val['uid'] === $id) {
           return $key;
       }
   }
   return null;
}

This will work. You should call it like this:

$id = searchForId('100', $userdb);

It is important to know that if you are using === operator compared types have to be exactly same, in this example you have to search string or just use == instead ===.

Based on angoru answer. In later versions of PHP (>= 5.5.0) you can use one-liner.

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

Here is documentation: http://php.net/manual/en/function.array-column.php.

Answer from Jakub Truneček 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 f. ...
🌐
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 - Use array_find to get one value. Use array_filter to collect many values. ... This example checks each value and stops once it finds the first even number.
🌐
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
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
🌐
ZetCode
zetcode.com › php-array › array-find
PHP array_find - Array Search in PHP
... <?php declare(strict_types=1); class User { public function __construct( public string $name, public int $age ) {} } $users = [ new User("Alice", 25), new User("Bob", 30), new User("Charlie", 22) ]; $youngUser = array_find($users, fn(User $u): bool => $u->age < 25); echo $youngUser?->name ??
🌐
PHP
wiki.php.net › rfc › array_find
PHP: rfc:array_find
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 ...
🌐
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 none of the elements returned true, the array_find_key function returns null. /** * Returns the KEY of the first element from $array for which the * $callback returns TRUE. If no matching element is found the * function returns NULL. * * @param array $array The array that should be searched.
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
🌐
3D Bay
clouddevs.com › home › php guides › working with php’s array_search() function: a practical guide
Working with PHP's array_search() Function: A Practical Guide
December 11, 2023 - 'Found at key ' . $strict : 'Value not found') . PHP_EOL; In this example, we have an array $fruits containing a mix of string and integer values. We perform both non-strict and strict searches for the value ‘3’. Here’s the output: vbnet ...
🌐
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 - Four new array functions are coming to PHP 8.4 which are helper functions for checking an array for the existence of elements matching a specific condition. The new functions are: ... The array_find($array, $callback) function returns the first element for which the $callback returns true:
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($xs, $f) {
  foreach ($xs as $x) {
    if (call_user_func($f, $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 $f($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($f, $x) instead of just calling $f($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($xs, $f) {
  foreach ($xs as $x) {
    if (call_user_func($f, $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; }); // []
🌐
W3Schools
w3schools.com › php › func_array_in_array.asp
PHP in_array() Function
connection_aborted() connection_status() connection_timeout() constant() define() defined() die() eval() exit() get_browser() __halt_compiler() highlight_file() highlight_string() hrtime() ignore_user_abort() pack() php_strip_whitespace() show_source() sleep() sys_getloadavg() time_nanosleep() time_sleep_until() uniqid() unpack() usleep() PHP MySQLi · affected_rows autocommit change_user character_set_name close commit connect connect_errno connect_error data_seek debug dump_debug_info errno error error_list fetch_all fetch_array fetch_assoc fetch_field fetch_field_direct fetch_fields fetch_l
🌐
W3docs
w3docs.com › learn-php › array-search.html
PHP Array Search: A Comprehensive Guide
The array_search() function is then used to search for the value in the array, and the result is stored in the $result variable. Finally, we use the echo statement to output the position of the value in the array.
🌐
GeeksforGeeks
geeksforgeeks.org › php › php-array_search-function
PHP array_search() Function - GeeksforGeeks
September 12, 2024 - It returns the index of the first ... (array_search($value, $array)); } $array = array( "ram", "aakash", "saran", "mohan", "saran" ); $value = "saran"; print_r(Search($value, $array)); ?>...
🌐
Tutorialspoint
tutorialspoint.com › php › php_function_array_search.htm
PHP - Function array_search()
It returns the key if it is found in the array, FALSE otherwise. Try out following example − · <?php $input = array("a"=>"banana","b"=>"apple","c"=>"Mango"); print_r(array_search("apple", $input)); ?> This will produce the following result − · b · php_function_reference.htm ·
🌐
Codecademy
codecademy.com › docs › php › arrays › array_search()
PHP | Arrays | array_search() | Codecademy
September 8, 2023 - Searches an array for a given value and returns the first matching key for that value.