Skip to content

Instantly share code, notes, and snippets.

@kellenmace
Last active May 21, 2020 15:49
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kellenmace/0395d57978db18d5495f11fead184fa7 to your computer and use it in GitHub Desktop.
Save kellenmace/0395d57978db18d5495f11fead184fa7 to your computer and use it in GitHub Desktop.
array_find() function for PHP
<?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;
}
@kellenmace
Copy link
Author

Example usage:

$names = [ 'Jerry', 'Newman' ];
$newmans_name = array_find( $names, fn( $name ) => $name === 'Newman' );
echo $newmans_name; // "Newman"

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment