Encodera

Thanks for reading!

Donate to the site — we work hard for you.

How to find an array element by a condition

Short answer

Since PHP 8.4 there is array_find() — it returns the first matching element or null:

<?php
 
$users = [['id' => 1, 'name' => 'Anna'], ['id' => 2, 'name' => 'Oleg']];
 
$user = array_find($users, fn ($item) => $item['id'] === 2);
 
echo $user['name'];

Output:

Oleg

Older PHP versions

Filter the array and take the first element of the result:

<?php
 
$users = [['id' => 1, 'name' => 'Anna'], ['id' => 2, 'name' => 'Oleg']];
 
$found = array_filter($users, fn ($item) => $item['id'] === 2);
$user = reset($found) ?: null;
 
echo $user['name'];

Output:

Oleg

The index by a field value

array_column() and array_search() find the position of the element:

<?php
 
$users = [['id' => 1, 'name' => 'Anna'], ['id' => 2, 'name' => 'Oleg']];
 
echo array_search(2, array_column($users, 'id'));

Output:

1

Functions used in this recipe

  • array_find — Returns the first element for which the function returned true.
  • array_filter — Keeps the array elements that pass a test.
  • reset — Returns the first element of an array.

Thanks for reading!

Donate to the site — we work hard for you.