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:

    [dimension_height] => 20
    [dimension_width] => 30
    [dimension_depth] => 40

Liked this post? Follow this blog to get more. 

Leave a Reply

You must be logged in to post a comment.

Panorama Theme by Themocracy

1 visitors online now
0 guests, 1 bots, 0 members
Max visitors today: 16 at 08:14 am UTC
This month: 17 at 19-09-2017 09:35 pm UTC
This year: 45 at 02-01-2017 10:28 pm UTC
All time: 130 at 28-03-2011 10:40 pm UTC