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

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";

}

For people who need this for both multidimensional and normal arrays, i have adapted it.

function array_find($needle, array $haystack, $column = null) {
    
    if(is_array($haystack[0]) === true) { // check for multidimentional array

        foreach (array_column($haystack, $column) as $key => $value) {
            if (strpos(strtolower($value), strtolower($needle)) !== false) {
                return $key;
            }
        }

    } else {
        foreach ($haystack as $key => $value) { // for normal array
            if (strpos(strtolower($value), strtolower($needle)) !== false) {
                return $key;
            }
        }
    }
    return false;
}

Here's an example:

$multiArray = array(
     0 => array(
              'name' => 'kevin',
              'hobbies' => 'Football / Cricket'),
      1 => array(
              'name' => 'tom',
              'hobbies' => 'tennis'),
       2 => array(
              'name' => 'alex',
              'hobbies' => 'Golf, Softball')
);
$singleArray = array(
        0 => 'Tennis',
        1 => 'Cricket',
);

echo "key is - ". array_find('cricket', $singleArray); // returns - key is - 1
echo "key is - ". array_find('cricket', $multiArray, 'hobbies'); // returns - key is - 0

Hope this helps someone. You could also check to see if the $column is found more than once and if some return an array of the keys matching.

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