PHP Search Multi Dimensional Arrays
PHP provides some nice functions (in_array, array_search) to check if a particular value exists inside an array, without the need for any additional for or while loops in your code. If you want to search an array that contains multiple dimensions e.g.
$array1 = array( 0 => array('name' => 'Joe') )
The standard PHP functions will not iterate through all levels in arrays that contain multiple dimensions. This is a bit useless if you have a result set from your database that spans multiple dimensions i.e.
$dbresult = array( <row number> => array(<fieldname> => <fielddata>) )
Examples I’ve seen around the web seem overly complex for what I require so I put together a really simple function, not the most efficient but if your result set is small it should do the trick. My database result array is in this format…
$dbresult = array( 123 => array('word_name' => 'Bazinga') )
I need to search the values contained in <fielddata>, the <row number> is an incremental number and can be ignored, I know the name of the <fieldname> that I want to search.
Below is example code and the search_multi_array function
find_word.php
include ('lib/class.word_game.php');
$game = new word_game();
$game->find_a_word('bazinga');
class.word_game.php
class word_game
{
function find_a_word($word)
{
// Returns the result set from the DB
$word_list = $this->load_word_list();
// Pass 3 args - word to find, multi dimensional array, field name
return $this->search_multi_array($word, $word_list, 'word_name');
}
function search_multi_array($find, $thearray, $key_name = null)
{
// Check our arguments are valid
if (!is_array($thearray) && !isset($find))
{
return false;
}
// Loop through row numbers
foreach ($thearray as $data)
{
// Define the key to use with our second array (<fieldname> => <fielddata>)
$data = (!is_null($key_name)) ? $data[$key_name] : $data;
// A match is found
if ($data == $find)
{
return true;
}
}
// No matches
return false;
}
}
When I get a bit more time I’ll try and build a much more efficient function to search multi dimensional arrays.

























nice function!, maybe turn it into a StringText search function, taking the emphasis of the costly db string text searches.
Pingback: Amedar Consulting
Pingback: PHP Extract Data from HTML - Gareth Coffey's blogGareth Coffey's blog
Pingback: fsgb80v7cbwe