Skip to content

Instantly share code, notes, and snippets.

@Chengings
Created March 17, 2014 18:12
Show Gist options
  • Save Chengings/9605009 to your computer and use it in GitHub Desktop.
Save Chengings/9605009 to your computer and use it in GitHub Desktop.
Search in array value with partial match
<?php
/**
* Seach in array value, similar to in_array(), but has ability to search with partial match
* @param string $needle searched value
* @param array $haystack target array
* @param string $return_key if third parameter is set to TRUE, the function will return array key
* @return boolean|int|string if found, function will return TRUE, string or int of first founded key (if return_key set to TRUE)
* otherwise FALSE
*/
function search_word_in_array($needle, $haystack, $return_key = FALSE) {
if (empty($needle) || empty($haystack)) {
return FALSE;
}
foreach ($haystack as $key => $value) {
// strpos return position (can be 0) if found, use !== to check type
if (strpos(strtolower($value), strtolower($needle)) !== FALSE) {
if ($return_key) {
return $key;
}
return TRUE;
}
}
return FALSE;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment