views:

432

answers:

3

I am working on accessing a db table that will read through a text entry to find a string...then based on that string, create a new variable.

Here's the source:

<?php

    $haystack = "Additional Licenses: +2 Licenses /br/ Back-up CD-ROM: No";
    $needle = "+0";

    switch ($needle) {
      case '+1':
          if (strstr($haystack, $needle)) {
              $actpurch = "3";
          } else {
              break;
          }
      case '+2':
          if (strstr($haystack, $needle)) {
              $actpurch = "4";
          } else {
              break;
          }
      case '+3':
          if (strstr($haystack, $needle)) {
              $actpurch = "5";
          } else {
              break;
          }
      default:
          $actpurch = "2";
          break;
    }

    echo "Activations Purchased:  " . $actpurch;

?>
A: 

Since $needle = "+0" you'll always end up in

default:
    $actpurch = "2";
    break;

You may want to read the manual's page about the switch statement again.

Philippe Gerber
How do I get it to reprot the CORRECT. Since $haystack will actually pull an entry from a db table (and it will change) depending on how many activations the customer purchases. So, the question is: How do I get the switch-case to work with a changing entry? The full text will remain the same except the "+#". Most will be '+0', but on the off chance it's not, I need to ensure that each customer is limited to the appropriate number of activations.
A: 

You’re switching on $needle, which has a fixed value of "+0". Thus only your default case will ever execute.

Nate
A: 

I wouldn't use a switch altogether. What you are trying to do is extract the number, which you can do with a regular expression, see the PHP Manual. An example:

$haystack = "Additional Licenses: +2 Licenses /br/ Back-up CD-ROM: No";
$licences = 2;

$extra = 0;
if (preg_match('/Additional Licenses: \+(\d+) Licenses/', $haystack, $matches)) {
        $extra = intval($matches[1]);
} else {
        die('Error: couldn\'t find number of licences');
}

$actpurch = $licences + $extra;
echo $actpurch;

The regular expression will match the string against the pattern (\d+ will match one or more digits).

John