0

So I think a switch might not be the most appropriate method of doing this, how else could I do it? Basically I want to break the string into single letters, then pass values for each letter to a new variable. What I have so far (with most letters taken out, so you can get the gist but I don't fill the screen):

$word = $_POST["word"];
$word_value = 0;
$word_array = str_split($word);

switch ($word_array){
    case "a":
    case "t":
        $word_value++;
        break;
    case "g":
    case "d":
        $word_value +2;
        break;
 }

Thanks in advance!

1
  • Use a letter value lookup table instead. Commented Jul 29, 2013 at 3:04

3 Answers 3

1

You insert the switch inside a foreach loop where you analyze every element of the array. $word_array is your array and $word is an element of the array.

$word = $_POST["word"];
$word_value = 0;
$word_array = str_split($word);

foreach($word_array as $letter){
    switch ($letter){
        case "a":
        case "t":
            $word_value++;
            break;
        case "g":
        case "d":
            $word_value+=2;
            break;
    }
}
Sign up to request clarification or add additional context in comments.

1 Comment

Shouldn't the $word in the switch case be $word_value? Right now, you'd just be increment, or adding to the letter itself.
1

Assuming that the values are constant, create a second array. This array holds the amount to increment for each letter. Now you don't need a switch statement, you simply index into the second array.

For example:

$letter_value["a"] = $letter_value["t"] = 1;
$letter_value["g"] = $letter_value["d"] = 2;

foreach ($word_array as $letter){
   $word_value += $letter_value[$letter];
}

Comments

1

Try something like:

class Word{
  private $pn = 'word'; private $wv = 0;
  public function __construct($postName){
    $this->pn = $postName;
  }
  public function change_postName($postName){
    $this->pn = $postName;
  }
  public function value(){
    $wA = str_split($_POST[$this->pn]);
    foreach($wA as $w){
      switch($w){
        case 'a':
        case 't':
          $this->wv++;
          return $this->wv;
        case 'g':
        case 'd':
        $this->wv+=2;
          return $this->wv;
      }
    }
  }
}
$wrd = new Word('word'); $word_value1 = $wrd->value();

Now you can change where you get your information like:

$wrd->change_postName('other'); $word_value2 = $wrd->value();

and reset your word value to zero, like:

$nwrd = new Word('word');

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.