Req #78176 [Opn]: New function array_search_callback() accepts a callable as $needle

From: Date: Tue, 18 Jun 2019 01:58:40 +0000
Subject: Req #78176 [Opn]: New function array_search_callback() accepts a callable as $needle
References: 1  Groups: php.bugs 
Request: Send a blank email to php-bugs+get-221354@lists.php.net to get a copy of this message
Edit report at https://bugs.php.net/bug.php?id=78176&edit=1 ID: 78176 Updated by: requinix@php.net Reported by: david at davidwbarratt dot com -Summary: array_search() should accept a callable as $needle +Summary: New function array_search_callback() accepts a callable as $needle Status: Open Type: Feature/Change Request -Package: *General Issues +Package: Arrays related PHP Version: Next Minor Version Block user comment: N Private report: N New Comment: It would be a breaking change: callables can be strings, arrays, __invoke-able objects, and Closures. There will be code out there that has arrays of those, and if array_search thinks its $needle may be callable then searching those arrays won't work. So this should be a new function. Probably "array_search_callback", like preg_replace_callback. Previous Comments: ------------------------------------------------------------------------ [2019-06-17 17:12:37] david at davidwbarratt dot com Description: ------------ It would be really helpful if array_search() would accept a callable as $needle. There are many instances where it is needed to loop through an array and stop and the first instance. Currently, the only work around is to make a function with a foreach() that returns early. This would bring PHP inline with JavaScript's Array.find() method. This change would not be a breaking change because array_search() would continue to work exactly as before the change. The only difference would be that now $needle can accept a callable that returns a boolean. This change would also make array_search() more like array_filter(). Test script: --------------- // Current function search( $haystack ) { foreach ( $haystack as $index => $value ) { if ( $value->id === 3 ) { return $value; } } return null; } $found = search( $haystack ); // Future $found = array_search( function( $value, $index ) { return $value->id === 3; }, $haystack ); ------------------------------------------------------------------------ -- Edit this bug report at https://bugs.php.net/bug.php?id=78176&edit=1

« previous php.bugs (#221354) next »