Skip to content

Instantly share code, notes, and snippets.

@2ndkauboy
Last active December 20, 2015 01:59
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save 2ndkauboy/6053457 to your computer and use it in GitHub Desktop.
Save 2ndkauboy/6053457 to your computer and use it in GitHub Desktop.
<?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;
});
}
@2ndkauboy
Copy link
Author

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.

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