Search Array Keys and Return Matches

By , Wednesday 13th August 2008 4:26 pm

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
)

Leave a Reply













Panorama Theme by Themocracy

8 visitors online now
1 guests, 7 bots, 0 members
Max visitors today: 23 at 10:05 am UTC
This month: 23 at 05-02-2012 10:05 am UTC
This year: 54 at 09-01-2012 07:56 pm UTC
All time: 130 at 28-03-2011 10:40 pm UTC