Skip to content

Instantly share code, notes, and snippets.

@aran112000
Last active August 28, 2019 10:02
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save aran112000/c77a8d8f4c41af6f5800b485caf94fa9 to your computer and use it in GitHub Desktop.
Save aran112000/c77a8d8f4c41af6f5800b485caf94fa9 to your computer and use it in GitHub Desktop.
Search a PHP array for a matching key - array_ksearch(), array_kisearch()
<?php
/**
* Search an array recursively looking for a key containing the supplied $search_string
*
* array_ksearch() is case-sensitive, where as array_kisearch() is case-insensitive
*
* Returns an array containing all matched key(s) and their associated value(s), or an empty array upon no matches
*
* @param array $array
* @param string $search_string
*
* @return array
*/
function array_ksearch(array $array, string $search_string): array {
$matches = [];
foreach ($array as $key => $value) {
if (strstr($key, $search_string)) {
$matches[$key] = $value;
}
if (is_array($value)) {
if ($recursive_response = array_ksearch($value, $search_string)) {
$matches = array_merge($matches, $recursive_response);
}
}
}
return $matches;
}
/**
* Search an array recursively looking for a key containing the supplied $search_string
*
* array_kisearch() is case-insensitive, where as array_ksearch() is case-sensitive
*
* Returns an array containing all matched key(s) and their associated value(s), or an empty array upon no matches
*
* @param array $array
* @param string $search_string
*
* @return array
*/
function array_kisearch(array $array, string $search_string): array {
$matches = [];
foreach ($array as $key => $value) {
if (stristr($key, $search_string)) {
$matches[$key] = $value;
}
if (is_array($value)) {
if ($recursive_response = array_kisearch($value, $search_string)) {
$matches = array_merge($matches, $recursive_response);
}
}
}
return $matches;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment