note 96293 deleted from function.array-search by danbrown

From: Date: Fri, 19 Feb 2010 17:21:39 +0000
Subject: note 96293 deleted from function.array-search by danbrown
References: 1  Groups: php.notes 
Request: Send a blank email to php-notes+get-166186@lists.php.net to get a copy of this message
Note Submitter: Sam Henry ---- This is a modified version of Jupiter's arrayHaystackStartsWithNeedleString() function. In this case, the function searches for array keys that START with the string and returns all values of those keys in a comma delimited format. This can be easily modified to output in an array format. There may be a more efficient method but I could not find one. - Sam <?php // returns all values of haystackarray for which array key starts with a specified string, case-sensitive function arraySearchKeysByPrefix($array, $string) { $result = ""; if (is_array($array)) { // confirms array $needlelength = strlen($string); // length of string needle foreach ($array as $arraykey => $arrayvalue) { // gets array key and value $arraypart = substr($arraykey, 0, $needlelength); // first characters of array key if ($string == $arraypart) { // chek for a match $result .= $arrayvalue.","; } // end match conditional } // end loop } // end array check $result = (substr($result,-1)==",") ? substr($result, 0, -1) : $result; //remove trailing comma return ($result=="") ? false:$result; // if no matches found return false, else return matches } //Example $haystack = array( 'key'=>'dontwant', 'want1'=>'want', 'key2'=>'dontwant', 'want2'=>'this', 'want3'=>'data'); //Output is: want,this,data ?>

« previous php.notes (#166186) next »