Last active
May 21, 2020 15:49
-
-
Save kellenmace/0395d57978db18d5495f11fead184fa7 to your computer and use it in GitHub Desktop.
array_find() function for PHP
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
/** | |
* Get the value of the first array element that satisfies the callback function. | |
* Similar to JavaScript's Array.prototype.find() method. | |
* | |
* @param array $array The array. | |
* @param callable $callback The callback function. | |
* | |
* @return mixed The value of the element, or null if not found. | |
*/ | |
function array_find( array $array, callable $callback ) { | |
foreach ( $array as $key => $value ) { | |
if ( $callback( $value, $key, $array ) ) { | |
return $value; | |
} | |
} | |
return null; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Example usage: