Search Array Keys and Return Matches

By Steven Lloyd Watkin, 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
)

Post to Twitter Tweet This Post Post to Plurk Plurk This Post Post to Yahoo Buzz Buzz This Post Post to Delicious Delicious Post to Digg Digg This Post Post to Facebook Facebook Post to MySpace MySpace Post to Ping.fm Ping This Post Post to Reddit Reddit Post to StumbleUpon Stumble This Post

Leave a Reply













Panorama Theme by Themocracy

9 visitors online now
2 guests, 7 bots, 0 members
Max visitors today: 12 at 12:36 am UTC
This month: 12 at 03-09-2010 12:36 am UTC
This year: 66 at 15-07-2010 02:49 am UTC
All time: 66 at 15-07-2010 02:49 am UTC