Last active
January 27, 2021 18:42
-
-
Save branneman/951847 to your computer and use it in GitHub Desktop.
array_find() - A case insensitive array_search() with partial matches
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 | |
/** | |
* Case in-sensitive array_search() with partial matches | |
* | |
* @param string $needle The string to search for. | |
* @param array $haystack The array to search in. | |
* | |
* @author Bran van der Meer <branmovic@gmail.com> | |
* @since 29-01-2010 | |
*/ | |
function array_find($needle, array $haystack) | |
{ | |
foreach ($haystack as $key => $value) { | |
if (false !== stripos($value, $needle)) { | |
return $key; | |
} | |
} | |
return false; | |
} |
If you're not afraid of a little bit of regex, preg_grep()
is native PHP and will likely do this more quickly:
https://www.php.net/manual/en/function.preg-grep.php
// Looking for "first " at beginning of any array values
// Get results
$results = array_values( preg_grep( '/^first (\w+)/i', array(
'f', 'fun', 'first', 'first match', 'not first'
) ) );
// Output
var_dump( $results );
// Results
array (size=1)
0 => string 'first match' (length=11)
The PREG_GREP_INVERT
flag even allows quickly targeting the inverse.
// Looking for inverse of "first " at beginning of any array values
// Get results
$results = array_values( preg_grep( '/^first (\w+)/i', array(
'f', 'fun', 'first', 'first match', 'not first'
), PREG_GREP_INVERT ) );
// Output
var_dump( $results );
// Results
array (size=4)
0 => string 'f' (length=1)
1 => string 'fun' (length=3)
2 => string 'first' (length=5)
3 => string 'not first' (length=9)
Note that I'm using /i
above to denote case insensitivity.
Very helpful. Thanks.
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
It saved me from a heart attack! Thank you so much!