4

array_fetch_item - fetch an array item by criteria

It's often the case that you'll need a single item from an array if it exist within a given criteria. You'd typically use array_filter to do this however this has some drawbacks. * It returns an array * You need to further process the resulting array to get your item * The syntax to do so can span several line of code. If you know your array will contain the required item you can extract it using a combination of array_filter and array_slice: ```php $my_array = [1, 2, 3]; array_slice(array_filter($my_array, function($item){ return $item === 2; }), 0, 1)[0]; // 2 ``` However this is quite a meaty bit of code just to get your item out. (I'd be interested in knowing an easier / cleaner way to extract an item) Suggesting the following function for PHP (not sure on the name): ```php array_fetch_item(array $array, callable $criteria); ``` - Returns the first item matching the given criteria (subsequent matches are ignored) - Returns false if no item is found - Does not modify the internal array pointer in $array Usage example: ```php $my_array = [1, 2, 3]; echo array_fetch_item($my_array, function($item){ return $item === 2; }); // 2 ```
Insolita ยท 2 months ago