Home > Back-end >  elseif value is less than getting value or greater than
elseif value is less than getting value or greater than

Time:05-20

I am trying to show echo 2 but its not working

$zipcode1 = 07300-011;
  $zipcode= str_replace("-","",$zipcode1);
$zipcode = 07300011;
   if ($zipcode >= 20000000 && $zipcode <= 26600999) { 
     echo '1';
}
   elseif ($zipcode >= 07000001 && $zipcode <= 07399999) { 

     echo '2';
}
else {
    echo 'no value';
    }
    

Please let me know where i am doing wrong. Thank you for the help Result = 2

CodePudding user response:

You need to compare string with string if the leading 0 of the zipcode is important:

$zipcode1 = "07300-011";
$zipcode= str_replace("-","",$zipcode1);
$zipcode = "07300011";
if ($zipcode >= "20000000" && $zipcode <= "26600999") { 
    echo '1';
} elseif ($zipcode >= "07000001" && $zipcode <= "07399999") { 
    echo '2';
} else {
    echo 'no value';
}

CodePudding user response:

You made two mistakes.

One is that the value assigned to $zipcode1 is not a string, but rather the result of an arithmetic operation. I'm saying $zipcode1 is not "07300-011", but rather 07300-011, which is equal to the octal number 7300 (3776 in base 10) minus octal 11 (9 in base 10), i.e 3776 - 9 which is 3767.

The second is that you're trying to do a numeric comparison using strings. "20" > "1000" is not the same as 20 > 1000. The first would resolve to true, whereas the second would give false (which is likely what you want). To fix this, you have to first convert both of them to numbers. You can either cast them:

((int) $zipcode1) > (int) $zipcode2

or you can use the sign instead:

( $zipcode1) > ( $zipcode2)

In both cases, you need to first remove whitespaces and every other non-numeric character from the zipcode.

$zipcode = str_replace([' ', '-'], '', $zipcode);

Read the following topics in the php docs for more info:

  1. Numeric Strings
  2. Comparison Operators
  • Related