CelestialDog Posted December 14, 2006 Share Posted December 14, 2006 Hi guys i'm new to php, still learning the ropes. I was hopeing someone may be able to give me a little help.Basically what i'm trying to do is compare a string against values held in an ascociative array. As an example i've created an array which holds each letter of the alaphabet as a key..and each letter holds a value starting at one like this...$testarray = array( "a" => "1", "b" => "2"); //and so onwhat i want to do is take a users name and compare each letter of the name against the value in the array. Iterateing through the array with a foreach loop is no problem, its just trying to compare the two. Any help would be greatfully apreciated.CD ;D Link to comment https://forums.phpfreaks.com/topic/30651-comparing-a-string-against-an-array/ Share on other sites More sharing options...
craygo Posted December 14, 2006 Share Posted December 14, 2006 Can try this[code]<?phpfunction letterfind($array, $string){ foreach($array as $letter){ if(strstr($string, $letter)){ $result = "YES"; break; } else { $result = "NO"; } }return $result;}$array = array('a','j','c','d','e','f','g');$string = "hhhhhjjrjjrj";echo letterfind($array, $string);?>[/code]Ray Link to comment https://forums.phpfreaks.com/topic/30651-comparing-a-string-against-an-array/#findComment-141230 Share on other sites More sharing options...
Psycho Posted December 14, 2006 Share Posted December 14, 2006 This is a little more efficient as it does not require you to manually iterate throught the array[code]<?phpfunction letterfind($array, $string){ for ($i=0; $i<strlen($string); $i++) { $letter = substr($string,$i,1); echo $letter . " = "; echo (array_search($letter, $array))?array_search($letter, $array):"Not in array"; echo "<br>"; }return $result;}$array = array('a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z');$string = "testing string";echo letterfind($array, $string);?>[/code] Link to comment https://forums.phpfreaks.com/topic/30651-comparing-a-string-against-an-array/#findComment-141317 Share on other sites More sharing options...
Recommended Posts
Archived
This topic is now archived and is closed to further replies.