note 96293 added to function.array-search

From: Date: Fri, 19 Feb 2010 05:56:54 +0000
Subject: note 96293 added to function.array-search
Groups: php.notes 
Request: Send a blank email to php-notes+get-166166@lists.php.net to get a copy of this message
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 ?> ---- Server IP: 69.147.83.197 Probable Submitter: 68.33.204.223 ---- Manual Page -- http://www.php.net/manual/en/function.array-search.php Edit -- https://master.php.net/note/edit/96293 Del: integrated -- https://master.php.net/note/delete/96293/integrated Del: useless -- https://master.php.net/note/delete/96293/useless Del: bad code -- https://master.php.net/note/delete/96293/bad+code Del: spam -- https://master.php.net/note/delete/96293/spam Del: non-english -- https://master.php.net/note/delete/96293/non-english Del: in docs -- https://master.php.net/note/delete/96293/in+docs Del: other reasons-- https://master.php.net/note/delete/96293 Reject -- https://master.php.net/note/reject/96293 Search -- https://master.php.net/manage/user-notes.php

« previous php.notes (#166166) next »