Last active
December 20, 2015 01:59
-
-
Save 2ndkauboy/6053457 to your computer and use it in GitHub Desktop.
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 | |
/** | |
* Search the array for a part of a string in the values and return an array with matching elements | |
* | |
* @param array $haystack The array. | |
* @param string $needle The searched value. | |
* @return array The filtered array. | |
*/ | |
function array_match_string(array $haystack, $needle){ | |
return array_filter($haystack, function($value) use ($needle){ | |
// You may use strpos for case-sensitive or preg_match for more complex searches | |
return stripos($value, $needle) !== false; | |
}); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
A simple function to search for a part of an array value (unlike array_search which searches for the full value). It returns an array with all elements, matching the search string in the value of the element (preserving the original index). This function requires PHP >= 5.3 as it uses the "use" keyword and an anonymous funtion. For lower PHP versions, check my alternative with two functions in this Stackoverflow answer.