Jump to content

Comparing a string against an array


CelestialDog

Recommended Posts

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 on

what 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

Can try this
[code]<?php
function 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
This is a little more efficient as it does not require you to manually iterate throught the array

[code]<?php
function 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]

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.