Joe
Joe

Reputation: 21

Using a switch with an array?

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!

Upvotes: 0

Views: 170

Answers (3)

StackSlave
StackSlave

Reputation: 10627

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');

Upvotes: 1

Jeff N
Jeff N

Reputation: 3429

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];
}

Upvotes: 1

Perocat
Perocat

Reputation: 1521

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;
    }
}

Upvotes: 1

Related Questions