Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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
You can’t perform that action at this time.