Find Array Element using array_find and array_find_key in PHP 8.4

Find Array Element using array_find and array_find_key in PHP 8.4

Since PHP 8.4, the array_find and array_find_key functions can be employed. These functions allow finding an array element by a custom condition. They provide an efficient way to search through arrays without needing to write custom loops. Additionally, they improve code readability by simplifying array search logic.

  • The array_find function returns the value of the first element in the array that satisfies the callback condition, or null if no such element is found.
  • The array_find_key function returns the key of the first element in the array that satisfies the callback condition, or null if no such element is found.
<?php

echo array_find([-2, -1, 0, 1, 2], fn (int $value) => $value > 0); // 1
echo array_find_key([-2, -1, 0, 1, 2], fn (int $value) => $value > 0); // 3

Leave a Comment

Cancel reply

Your email address will not be published.