tags:

views:

30

answers:

3

First question: For the case where the device_id is 2 the output is two, but any other case the output is still 2. Why is this?

if ($line == "IMEI 358998018395510\r\n"){
     $device_id = 1;
     }elseif($line == "IMEI 352924028650492\r\n"){
     $device_id = 3;
     }else {
     $device_id = 2;
}

Second question: I would like to replace the else statement above with the following:

..
elseif ($line == "$GPVTG,0,T,0,M,0,N,0,K,A*23\r\n"){
    $device_id = 2;
}

but the problem is that, the parser is faulting part of the string above picking out "$GPVTG" as undefined. Thought it should treat it as a whole string because it is in quotes?

+3  A: 
  1. None of your conditions match, so it falls through to the else clause.

  2. Double quotes allow variable substitution. Escape the $ or use single quotes.

Ignacio Vazquez-Abrams
Thanks for that idea.
ibiangalex
A: 

In PHP variables written in double quotes are evaluated at run time, and $ is used to represent the variable so you need to escape the $ in your condition.

Ummar
Thanks for that
ibiangalex
A: 

I realised that I could do the following and decided to use it. It works just fine. Thanks for all your contributions.

switch ($lineTokens[0]){
                case "IMEI 358998018395510\r\n":
                    $device_id = 1;
                    break;
                case "IMEI 352924028650492\r\n":
                    $device_id = 3;
                    break;
                case '$GPVTG':
                    $device_id = 2;
                    break;

            }       

Just to add: Similar to what some have suggested, I had to determine when to use single or double quotes as in the last CASE statement, escaping them when necessary. I used $linetokens instead of $line as previously submitted after exploding the $line. This enabled me to only find a match for '$GPVTG' instead of the whole $line which is not unique.

ibiangalex