Re: "Search" code finds ANYTHING

From: Date: Thu, 16 Aug 2001 02:12:12 +0000
Subject: Re: "Search" code finds ANYTHING
References: 1  Groups: php.general 
Request: Send a blank email to php-general+get-62934@lists.php.net to get a copy of this message
"Raphael Pirker" <raphaelp@nr1webresource.com> wrote in message news:20010816011955.66880.qmail@pb1.pair.com... > function search_the_array($array) { > global $search_tmp; > $result = array_search($search_tmp, $array, TRUE); > reset($array); > while (!($result === FALSE) && (list($k, $v) = each($array))) > { > // Or maybe you wanted ereg($search_tmp, $v) here... > $result = ereg($v, $search_tmp) ? $k : FALSE; > } > return ' '.$result; // extra space needed before the "key" > } This is a bit screwy... First, array_search returns an array of keys where the values are exact matches... while you want to match a substring (I think); Then, it searches through the array again using regular expressions, and each time it finds something, it over-writes all previous values... and if there were any matches to begin with, it WILL find them again. And why is the search-string passed as a global while the array is passed by value?! This makes no sense to me. Finally, result is passed back as a string after being munged so it can't be used as a key - and if nothing was found, it returns a string consisting of a single space. Try one of these instead: // util function: case-sensitive search for substring, // returns true if found, else false function findSameCase($haystack, $needle) { return (strpos($haystack, $needle) !== false); } // util function: case-insensitive search for substring, // returns true if found, else false function findAnyCase($haystack, $needle) { return (strpos(strtolower($haystack), strtolower($needle)) !== false); } // return the key of the first array member containing the search string, // or false if there are no matches. function findFirst($arr, $string, $caseSensitive=false) { if ($caseSensitive) $find = "findSameCase"; else $find = "findAnyCase"; foreach($arr as $key => $val) if ($find($val, $string)) return $key; return false; } // return an array of all keys to members containing the search // string (if there are no matches, the array is empty). function findAll($arr, $string, $caseSensitive=false) { if ($caseSensitive) $find = "findSameCase"; else $find = "findAnyCase"; $result = array(); foreach($arr as $key => $val) if ($find($val, $string)) $result[] = $key; return $result; }

« previous php.general (#62934) next »