Create a gist now

Instantly share code, notes, and snippets.

What would you like to do?
array_find() - A case insensitive array_search() with partial matches
<?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;
}

Thanks! This was helpful to me, but you've got the params in stripos backwards. Line 14 should be:

if (false !== stripos($value, $needle)) {

cmfcmf commented Jul 1, 2013

Thank you too @branneman! But as @heylookitsme said, the two params must be swaped.

Owner

branneman commented Aug 5, 2013

Fixed! Thanks :)

Super helpful, thanks!

Took me a good ten min to work out why nothing was matching!! Thanks, this is a handy snippet.

nycmitch25 commented Dec 31, 2016 edited

Major issue with the code: Fix the return on error .... it needs to return -1 on a failure, or something OTHER THAN a valid key value. This is because key values start with 0 , hence "false" or "null" etc... makes it hard ... ok impossible to validate this.

// check and set the value using -1 as the return
if ($key = array_find($search_term, $the_array_to_be_searched)) !== -1) {
echo "Found! In Array ".$the_array_to_be_searched[$key]." array value";

}

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