Happy Codings - Programming Code Examples
Html Css Web Design Sample Codes CPlusPlus Programming Sample Codes JavaScript Programming Sample Codes C Programming Sample Codes CSharp Programming Sample Codes Java Programming Sample Codes Php Programming Sample Codes Visual Basic Programming Sample Codes

Php Programming Code Examples

Php > Arrays Code Examples

Array Searching Recursively

Array Searching Recursively The following code will probably be understood better by advanced user, this code will only search array elements. <? // the function that will recursivly search an array. function searchArrayRecursive($needle, $haystack){ // loop through the haystack that has been passed in foreach ($haystack as $key => $arr) { // check to make sure that the element is an array if(is_array($arr)) { /* this is the tricky line, this will take the value or $arr and call the function again each time the function is called, $ret is set with the return value of the function call, this builds the string that get's returned. */ $ret=searchArrayRecursive($needle, $arr); /* check to make sure that the function call did not return -1 and return the value of the $key and the $ret */ if($ret!=-1) return $key.','.$ret; } else { /* check the array element and see if it matches the search term. if it does, return the $key of the element. */ if($arr == $needle) return (string)$key; } } // nothing was found, return -1 return -1; } // create the actual array to use ;) $myArray = array ( "computer" => array( "hardware" => array( "modem", "hard drive", "ram", "mother board" ), "softare" => array( "photoshop", "quickbooks" ) ), "cars" => array( "honda" => array( "civic", "accord" ), "toyota" => array( "4Runner", "camry", "carolla", "rav4", "tundra" ) ), "books" => array( "php" => array( "sams teach yourself php mysql and apache", "core php programming" ) ) ); // nicely format and print the value of $myArray print "<pre>"; print_r($myArray); print "</pre>"; // set the value to find in the array $findWhat = "tundra"; // call the function with the needle and haystack. $result = searchArrayRecursive($findWhat, $myArray); // check to make sure the returned result was not -1 if($result != -1) { /* create the result array from the string returned from the function. */ $result = explode(',', $result); /* Loop through the array to create an array format string such as $array[this][that][0] */ foreach($result as $element) { // append the element to the $result string $result .= '['.$element.']'; } } // check to make sure the result of the function is not -1 if($result != -1) { // tell us we found what we were looking for. echo 'Found '.$findWhat.'! '.$result; } else { /* tell us that we didnt find any array keys matching the search term. */ echo 'Couldn\'t Find <b>\''.$findWhat.'\'</b> in the array.'; } ?>