Search Array Keys and Return Matches
Aug 13th, 2008 by Steven Lloyd Watkin
I’ve had the need to search through an array and return the elements that have keys that match a search term. So I thought I’d share.
‘Why would I need this?’ would probably be the first question you’d ask, well if I wanted to search through an array for all the elements that related to the dimensions of an item then I could pull out the appropriate keys by using this little function:
<?
function searchArrayKey($array,$search)
{
$search = strtolower($search);
if (is_array($array))
{
foreach ($array as $key => $data)
{
if (strpos(strtolower($key),$search) === 0) { $returnArray[$key] = $data; }
}
return $returnArray;
} else
{ // User hasn't subimitted an array...
return false;
}
}
?>
So for example if I wanted to search an array of item data for the dimension data then I could do the following (and print to screen presumably):
$dimensions = searchArrayKeys($itemArray,'dimension');
Which would return something like:
print_r($dimensions);
Array
(
[dimension_height] => 20
[dimension_width] => 30
[dimension_depth] => 40
)





