Last active
August 28, 2019 10:02
-
-
Save aran112000/c77a8d8f4c41af6f5800b485caf94fa9 to your computer and use it in GitHub Desktop.
Search a PHP array for a matching key - array_ksearch(), array_kisearch()
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 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